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 で非同期メソッドを呼び出す必要がありますか?

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;DR

+ (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 に答える