繁体   English   中英

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

[英]Return Response data from nsurlconnection delegate method

嗨,我正在使用Web服务进行注册,我制作了一个单独的类来访问Web服务并在View类上返回响应。

这是我在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];
 }

调用getDataFromService方法后,它将调用returnRespnoseData方法。 然后,它调用从getDataFromService调用的连接方法。 所以我从returnResponseData得到了nil响应。 谁能告诉我如何管理它,或者如何将didfinishloading方法的响应返回给主视图类? 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];
 }

在连接上一个方法时,我在字典中得到了响应,如jsonDec

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

返回jsonDec到View类

-(NSDictionary *)returnResponseData
{
 return _jsonDec;
}

问题是您要在取回数据之前调用returnResponseData。

假设您要取回数据,您将看到日志以意外的顺序返回。

-(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;
}

您将需要等到didFinishConnection被调用,然后才能使用_jsonDec进行任何操作。 另外,如果您要更新UI,则可能要确保您位于MainThread上。 “如果”我的内存正确,则didFinishConnection可能不会返回主线程。

为确保应用程序在响应到达后将jsondata返回给viewclass,请在您的类的.h文件中定义一个块:

typedef void(^getDataBlock)(id jsonObject);

然后,您的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);
}];
}

在您的视图类中,您现在可以执行以下操作:

-(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