簡體   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