2014-02-17 3 views
0

Я создал службу WCF для вставки данных в sql-сервер, так что почему я следовал ниже структуры.Использовать службу WCF в xcode 5 и ios 7

Я создал сначала метод и его реализацию;

В WCF интерфейса:

[OperationContract] 
[WebInvoke(Method = "POST", 
    ResponseFormat = WebMessageFormat.Json, 
    RequestFormat = WebMessageFormat.Json, 
    BodyStyle = WebMessageBodyStyle.Wrapped, 
    UriTemplate = "json/InsertEmployee/{id1}/{id2}/{id3}")] 
bool InsertEmployeeMethod(string id1,string id2, string id3); 

соисполнители:

public bool InsertEmployeeMethod(string id1, string id2, string id3) 
    { 

     int success = 0; 

     using (SqlConnection conn = new SqlConnection("Data Source=NXT1;User ID=zakaria;Password=11;Initial Catalog=EmpDB;Integrated Security=false")) 
     { 
      conn.Open(); 

      decimal value = Decimal.Parse(id3); 
      string cmdStr = string.Format("INSERT INTO EmpInfo VALUES('{0}','{1}',{2})", id1, id2, value); 
      SqlCommand cmd = new SqlCommand(cmdStr, conn); 
      success = cmd.ExecuteNonQuery(); 

      conn.Close(); 
     } 

     return (success != 0 ? true : false); 
    } 

для тестирования веб-сервиса, попробуйте этот URL:

"41.142.251.142/JsonWcfService/GetEmployees.svc/json/InsertEmployee/myName/MylastName/6565" 

, пока здесь все работает хорошо,

Итак, чтобы протестировать этот веб-сервлет, я создал в своем TextFields Main.storyboard 3 (firstName.text и lastName.text и pay.text и кнопку для отправки введенных данных). обратите внимание, что я работал с Xcode 5 и КСН 7.

Я объявил URL внутри моего viewcontroller.m следующим образом: myViewController.m:

#define BaseWcfUrl [NSURL URLWithString:@"41.142.251.142/JsonWcfService/GetEmployees.svc/json/InsertEmployee/{id1}/{id2}/{id3}"] 

Тогда я осуществил Вставить метод Сотрудник, связанные с нажмите кнопка.

-(void) insertEmployeeMethod 

{ 

if(firstname.text.length && lastname.text.length && salary.text.length) 

{ 

NSString *getValue= [BaseWcfUrl stringByAppendingFormat:@"InsertEmployee/%@/%@/%@",firstname.text,lastname.text,salary.text]; 

NSURL *WcfServiceURL = [NSURL URLWithString:getValue]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

[request setURL:WcfServiceURL]; 

[request setHTTPMethod:@"POST"]; 

// connect to the web 

NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

// NSString *respStr = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding]; 


NSError *error; 

NSDictionary* json = [NSJSONSerialization 

         JSONObjectWithData:respData 

         options:NSJSONReadingMutableContainers 

         error:&error]; 



NSNumber *isSuccessNumber = (NSNumber*)[json objectForKey:@"InsertEmployeeMethodResult"]; 
    } 

} 

Так что вопрос, который я столкнулся в том, что система всегда возвращает значение ул как «Nil»

NSString *getValue= [BaseWcfUrl stringByAppendingFormat:@"InsertEmployee/%@/%@/%@",firstname.text,lastname.text,salary.text]; 

так что вы можете увидеть все ошибки сообщения:

2014-02-17 19:49:49.419 InsertData[2384:70b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil' * First throw call stack:

0 CoreFoundation 0x017395e4 __exceptionPreprocess + 180

1 libobjc.A.dylib 0x014bc8b6 objc_exception_throw + 44

2 CoreFoundation 0x017393bb +[NSException raise:format:] + 139

3 Foundation 0x012037a2 +[NSJSONSerialization JSONObjectWithData:options:error:] + 67

4 InsertData 0x0000236c -[ViewController sendData:] + 1452

5 libobjc.A.dylib 0x014ce874 -[NSObject performSelector:withObject:withObject:] + 77

6 UIKit 0x0022c0c2 -[UIApplication sendAction:to:from:forEvent:] + 108

7 UIKit 0x0022c04e -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61

8 UIKit 0x003240c1 -[UIControl sendAction:to:forEvent:] + 66

9 UIKit 0x00324484 -[UIControl _sendActionsForEvents:withEvent:] + 577

10 UIKit 0x00323733 -[UIControl touchesEnded:withEvent:] + 641

11 UIKit 0x0026951d -[UIWindow _sendTouchesForEvent:] + 852

12 UIKit 0x0026a184 -[UIWindow sendEvent:] + 1232

13 UIKit 0x0023de86 -[UIApplication sendEvent:] + 242

14 UIKit 0x0022818f _UIApplicationHandleEventQueue + 11421

CoreFoundation 0x016c283f CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 15

16 CoreFoundation 0x016c21cb __CFRunLoopDoSources0 + 235

17 CoreFoundation 0x016df29e __CFRunLoopRun + 910

18 CoreFoundation 0x016deac3 CFRunLoopRunSpecific + 467

19 CoreFoundation 0x016de8db CFRunLoopRunInMode + 123

20 GraphicsServices 0x036de9e2 GSEventRunModal + 192

21 GraphicsServices 0x036de809 GSEventRun + 104

22 UIKit 0x0022ad3b UIApplicationMain + 1225

23 InsertData 0x00002d5d main + 141

24 libdyld.dylib 0x01d7770d start + 1

) libc++abi.dylib: terminating with uncaught exception of type NSException

Можете ли вы, пожалуйста, помочь мне в этом, я очень стеснен.

очень оцените.

ответ

0

Я думаю, что у вас только неправильный URL, вы добавляете InsertEmployee дважды.

Изменение BaseWcfUrl только [NSURL URLWithString:@"41.142.251.142/JsonWcfService/GetEmployees.svc/json/"] вместо [NSURL URLWithString:@"41.142.251.142/JsonWcfService/GetEmployees.svc/json/InsertEmployee/{id1}/{id2}/{id3}"]

Чтобы быть абсолютно уверены, бревенчатый окончательный URL в консоли (или смотреть на него в отладчике), чтобы убедиться, что это правильно.

Кроме того, в вашем коде, в NSURL *WcfServiceURL = [NSURL URLWithString:str];, где str? Возможно, вы имели в виду getValue?

+0

Привет, спасибо за ваш ответ, я редактировал str для getValue. Я сделаю то, что вы предлагаете, и вернитесь к вам –

+0

Я изменил BaseWcfUrl на URL-адрес "[NSURL URLWithString: @" 41.142.251.142/JsonWcfService/GetEmployees.svc/json/ "]" –

+0

Я изменил BaseWcfUrl на URL-адрес " [NSURL URLWithString: @ "41.142.251.142/JsonWcfService/GetEmployees.svc/json/"] " , но теперь в системе появляется другая ошибка; [NSURL stringByAppendingFormat:]: непризнанный селектор, отправленный в экземпляр 0x8a630b0. завершение приложения из-за неперехваченного исключения 'NSInvalidArgumentException', 'reason:' - [NSURL stringByAppendingFormat:]: непризнанный селектор, отправленный в экземпляр 0x8a630b0 –

Смежные вопросы