如何使用NSURL sendAsynchronousRequest显示获取数据

时间:2014-10-12 02:07:14

标签: ios objective-c nsurlconnection sendasynchronousrequest

我看过很多关于nsurl异步的教程。我按照这些教程并实施了以下内容。

-(id) connect_asych:(NSDictionary *)input page:(NSString *)page{
    NSString* urlString= [@"*s.com/music/" stringByAppendingString:page];
    NSURL *url = [NSURL URLWithString:urlString];
    //initialize a request from url
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];

    //set http method
    [request setHTTPMethod:@"POST"];
    //initialize a post data

    NSString *post = [self convert:input];


    //set request content type we MUST set this value.

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    //set post data of request
    [request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
    NSError *error = nil;
    NSHTTPURLResponse *responseCode = nil;
    NSOperationQueue *queue = [NSOperationQueue mainQueue];


    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError  *error1) {
      if(error !=nil){

          _responseData=nil;

      }
        [_responseData appendData: data];
      NSLog(@"%@",_responseData);
    }];


    id object = [NSJSONSerialization JSONObjectWithData:_responseData options:NSJSONReadingAllowFragments error:&error];
    if(error !=nil){
        _error=[[NSString alloc] initWithFormat:@"error"];
        return error;
    }
    return object;
}

如果我的viewdidload,我调用了上面的方法。

我使用同步方法成功地从数据库中获取了数据。问题是当我使用异步方法时,我无法获取数据。我应该在viewdidload中调用异步方法吗?

2 个答案:

答案 0 :(得分:0)

您正在使用异步方法但不等待其执行

在异步调用之后立即使用

_responseData。此时您的呼叫未完成,因此未设置_responseData。

您必须在connect_async方法中提供一个回调块,并在sendAsynchronousRequest完成时执行该回调。

我写了一些评论

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError  *error1) {
    if(error !=nil) {
        _responseData=nil;
    }

    [_responseData appendData: data];
    // right here you have to execute some callback function

    NSLog(@"%@",_responseData);
}];

// at this time your sendAsynchronousRequest is not finished
// _responseData will always be unset at this time
id object = [NSJSONSerialization JSONObjectWithData:_responseData options:NSJSONReadingAllowFragments error:&error];
if(error !=nil) {
    _error=[[NSString alloc] initWithFormat:@"error"];
    return error;
}

// note: it's always a bad idea to try to return a result of an asynchronous call this way. It will never work because of the asynchronous nature.
return object;

有关如何实现回调块的信息

  

请参阅此答案:Implementing a method taking a block to use as callback

<强> TL; DR

+ (void)myMethod:(UIView *)exampleView completion:(void (^)(BOOL finished))completion {
    if (completion) {
        completion(finished);
    }
}

答案 1 :(得分:-1)

你必须在[_responseData appendData:data]之后在同一个块juste中添加数据处理;