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

时间:2015-03-12 10:56:44

标签: ios objective-c iphone web-services

您好我正在使用Web服务进行注册,我已经创建了一个单独的类来访问Web服务并在视图类上返回响应。

这是我的代码      在按钮上

-(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调用的连接方法。所以我收到nil的{​​{1}}回复。 任何机构都可以告诉我如何管理它或如何将响应从returnResponseData方法返回到主视图类? 在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

将jsonDec返回给View类

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

2 个答案:

答案 0 :(得分:1)

问题是你在获取数据之前调用了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;
}

在使用_jsonDec执行任何操作之前,您需要等到didFinishConnection被调用。此外,如果您要更新UI,您可能需要确保您在MainThread上。 "如果"我的记忆是正确的didFinishConnection可能不会回到主线程上。

答案 1 :(得分:1)

要确保应用程序在响应到达后将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"];
    });
}];
}