简体   繁体   English

从nsurlconnection委托方法返回响应数据

[英]Return Response data from nsurlconnection delegate method

Hi I am using a webservice for registration, I have made a separate class to hit the webservice and return the response on view class. 嗨,我正在使用Web服务进行注册,我制作了一个单独的类来访问Web服务并在View类上返回响应。

Here is my code on Button 这是我在Button上的代码

-(IBAction)placeOrder:(id)sender
 {               
 url = [[NSURL alloc]initWithString:@"http://54.25fdg.239.126/tfl/index.php/service/register"];
 NSString *str = [NSString stringWithFormat:@"name=%@&phoneNumber=%@&emailAddress=%@&password=%@&addressLine1=%@&addressLine2=%@&city=%@&pincode=%@&landmark=%@&specialInstruction=%@",txtUserName.text,txtPhone.text,txtEmail.text,txtPassword.text,addressLine1Tf.text,addressLine2Tf.text,cityTf.text,pinCodeTf.text,landMarkTf.text,specialInstrTv.text];
 WebServices *webservice = [[WebServices alloc]init];
 [webservice getDataFromService:url data:str];
 responseDictionary = [webservice returnResponseData];
 }

After calling the getDataFromService method it calls returnRespnoseData method. 调用getDataFromService方法后,它将调用returnRespnoseData方法。 Then it call the connection method which is called from getDataFromService . 然后,它调用从getDataFromService调用的连接方法。 So I got the nil response from returnResponseData . 所以我从returnResponseData得到了nil响应。 Can any body tell me how can I manage it or how can I return the response from didfinishloading method to main view class? 谁能告诉我如何管理它,或者如何将didfinishloading方法的响应返回给主视图类? In webservice.m webservice.m

-(void)getDataFromService:(NSURL *)url data:(NSString *)parameterString
 {
  NSData *postData = [parameterString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  [request setURL:url];
  [request setHTTPMethod:@"POST"];
  [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
  [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  [request setHTTPBody:postData];
  NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
  [conn start];
 }

In connection last method I have got the response in a dictionary as jsonDec . 在连接上一个方法时,我在字典中得到了响应,如jsonDec

 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError* error ;
 _jsonDec = [NSJSONSerialization JSONObjectWithData:_responseData options:NSJSONReadingAllowFragments error:&error];
}

Return the jsonDec to View class 返回jsonDec到View类

-(NSDictionary *)returnResponseData
{
 return _jsonDec;
}

The issue is you are calling returnResponseData before you get the data back. 问题是您要在取回数据之前调用returnResponseData。

Assuming you are getting data back you will see that logs come back in an unexpected order. 假设您要取回数据,您将看到日志以意外的顺序返回。

-(IBAction)placeOrder:(id)sender
{
    NSLog(@"Button Pressed");     
    url = [[NSURL alloc]initWithString:@"http://54.254.239.126/tfl/index.php/service/register"];
    NSString *str = [NSString stringWithFormat:@"name=%@&phoneNumber=%@&emailAddress=%@&password=%@&addressLine1=%@&addressLine2=%@&city=%@&pincode=%@&landmark=%@&specialInstruction=%@",txtUserName.text,txtPhone.text,txtEmail.text,txtPassword.text,addressLine1Tf.text,addressLine2Tf.text,cityTf.text,pinCodeTf.text,landMarkTf.text,specialInstrTv.text];
    WebServices *webservice = [[WebServices alloc]init];
    [webservice getDataFromService:url data:str];
    responseDictionary = [webservice returnResponseData];
}

-(void)getDataFromService:(NSURL *)url data:(NSString *)parameterString
{
    NSLog(@"Getting Data");
    NSData *postData = [parameterString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [conn start];
 }

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Finished getting data");
    NSError* error ;
    _jsonDec = [NSJSONSerialization JSONObjectWithData:_responseData options:NSJSONReadingAllowFragments error:&error];
}

-(NSDictionary *)returnResponseData
{
    NSLog(@"Returning data");
    return _jsonDec;
}

You will need to wait until didFinishConnection is called before doing anything with _jsonDec. 您将需要等到didFinishConnection被调用,然后才能使用_jsonDec进行任何操作。 Also if you are updating UI you may want to make sure you are on the MainThread. 另外,如果您要更新UI,则可能要确保您位于MainThread上。 "If" my memory is correct didFinishConnection may not come back on the main thread. “如果”我的内存正确,则didFinishConnection可能不会返回主线程。

To make sure that the app will return the jsondata to viewclass after the response has arrived define a block in the .h-file of your class: 为确保应用程序在响应到达后将jsondata返回给viewclass,请在您的类的.h文件中定义一个块:

typedef void(^getDataBlock)(id jsonObject);

Then your getDataFromService-method could look like this: 然后,您的getDataFromService方法可能如下所示:

-(void)getDataFromService:(NSURL *)url data:(NSString *)parameterString getDataBlock:(getDataBlock)returnBlock{
NSLog(@"Getting Data");
NSData *postData = [parameterString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSError *error = [[NSError alloc] init];
    id jsonDec = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    returnBlock(jsonDec);
}];
}

In your view class you can do this now: 在您的视图类中,您现在可以执行以下操作:

-(void)test{
//Insert the right name for your class where you do the request and insert the right values
[backendClass getDataFromService:[NSURL URLWithString:@"www.google.de"] data:@"blablabla" getDataBlock:^(id jsonObject) {
   //Make sure you're on the mainthread for UI-updates
    dispatch_async(dispatch_get_main_queue(), ^{
        self.titleLabel.text = [jsonObject objectForKey:@"title"];
    });
}];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM