如果方法使用NSURLConnection,则如何返回输出使用块进行异步调用 [英] How to return the ouput if method is using NSURLConnection Asynchronous calls with blocks

查看:111
本文介绍了如果方法使用NSURLConnection,则如何返回输出使用块进行异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向服务器发送请求以使用NSURLConnection块方法获取响应。我无法使用返回YES或在块中返回NO。我该如何解决这个问题?

I am sending request to server to get response using NSURLConnection blocks method. I am not able to use return YES or return NO in the block. How can i fix this?

-(BOOL)checkForValidUrl:(NSString *)url
{
       __block int httpStatus=0;
        NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url]];
        [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];


        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response, NSData *responseData, NSError *error)
         {
            httpStatus = [((NSHTTPURLResponse *)response) statusCode];
             NSLog(@"httpStatus inside block:%d",httpStatus);


         }
         ];

        return NO;
}


推荐答案

不要退货,但是通过一个完成块,然后通知调用者检查结果。您将不得不重新调整代码而不需要立即结果。

Don't return anything, but instead pass a completion block that later informs the caller of the results of the check. You will have to rework the calling code to not need an immediate result.

例如,假设200响应意味着URL有效:

e.g., assuming a 200 response means the URL was valid:

-(void)checkForValidUrl:(NSString *)url completion:(void (^)(BOOL validURL))completion {
  __block int httpStatus=0;
  NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url]];
  [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
  [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];


  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
    completionHandler:^(NSURLResponse *response, NSData *responseData, NSError *error) {
      httpStatus = [((NSHTTPURLResponse *)response) statusCode];
      NSLog(@"httpStatus inside block:%d",httpStatus);

      completion(200 == httpStatus);
    }
  ];
}

这篇关于如果方法使用NSURLConnection,则如何返回输出使用块进行异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆