0

HTTP POST リクエストと NSURLRequest を使用して JSON データを解析しています。しかし、sendAsynchronousRequest の下の値を取得した場合、その要求の外側でそれらを使用することはできません。以下の例を参照してください。

[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         NSError *parseError = nil;
         dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
         NSLog(@"Server Response (we want to see a 200 return code) %@",response);
         NSLog(@"dictionary %@",dictionary);
     }];

私の質問は、必要な場所で辞書の値を使用するにはどうすればよいですか? ありがとう

4

1 に答える 1

2

さまざまな方法でそれを行うことができます。1 つの方法は、プロパティを宣言し、ブロック内で使用することです。

非同期呼び出しを行っているため、これらの呼び出しに応答する独自のカスタム ブロックを用意することをお勧めします。

最初に完了ブロックを宣言します。

 typedef void (^ ResponseBlock)(BOOL success, id response);

このブロックをパラメーターとして使用するメソッドを宣言します。

 - (void)processMyAsynRequestWithCompletion:(ResponseBlock)completion;

このメソッドに非同期呼び出しを含めます。

- (void)processMyAsynRequestWithCompletion:(ResponseBlock)completion{

 [NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     NSError *parseError = nil;
     dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
     NSLog(@"Server Response (we want to see a 200 return code) %@",response);
     NSLog(@"dictionary %@",dictionary);
     completion(YES,response); //Once the async call is finished, send the response through the completion block
 }];

}

このメソッドは、好きな場所で呼び出すことができます。

 [classInWhichMethodDeclared processMyAsynRequestWithCompletion:^(BOOL success, id response) {
      //you will receive the async call response here once it is finished.
         NSDictionary *dic = (NSDictionary *)response;
       //you can also use the property declared here
           _dic = (NSDictionary *)response; //Here dic must be declared strong
 }];
于 2016-11-15T20:18:24.457 に答える