0

我看过很多关于 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 中调用异步方法吗?

4

2 回答 2

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;

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

请参考这个答案:实现一个将块用作回调的方法

TL;博士

+ (void)myMethod:(UIView *)exampleView completion:(void (^)(BOOL finished))completion {
    if (completion) {
        completion(finished);
    }
}
于 2014-10-12T02:43:38.867 回答
-1

您必须在 [_responseData appendData: data] 之后的同一块中添加数据队列;

于 2014-10-12T02:28:23.823 回答