如何,如果方法是使用NSURLConnection的异步返回的输出中有块调用(How to retu

2019-10-30 11:17发布

我发送请求到服务器,以获得使用NSURLConnection的块的方法应对。 我不能够使用返回YES或NO返回块中。 我怎样才能解决这个问题?

-(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;
}

Answer 1:

不要返回任何东西,而是通过完成块,后来通知检查结果的调用者。 你将不得不返工调用代码并不需要一个直接结果。

例如,假设一个200响应装置的URL是有效的:

-(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);
    }
  ];
}


Answer 2:

不可能。 当应用程序调用连接的结果是不知道return的语句。 你应该使用类似

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

           [_your_delegate_object connectionFinishedWithStatus:httpStatus data:responseData];

         }
         ];


Answer 3:

它应该是这样的

-(void)checkForValidUrl:(NSString *)url completion:(void(^)(BOOL success))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(httpStatus == 200) //if Yes or No depends on the status

     }
     ];
}


Answer 4:

您DataFetchController.h文件

- (void)beginLeadTaskWithCallbackBlock:(void (^)(NSArray *))callbackBlock;

您DataFetchController.m文件

-(void)beginLeadTaskWithCallbackBlock:(void (^)(NSArray *))callbackBlock{


// add your post code here


   [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)

    {
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
         if ([data length] >0 && error == nil && [httpResponse statusCode] == 200)
         {


             NSArray *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];


             NSLog(@"data %@",dictionary);
             callbackBlock(dictionary);

         }

     }];

}

块调用您的视图控制器

弱使用了避免内存泄漏

 DataFetchController *getFetch=[[DataFetchController alloc]init];
 DataFetchController * __weak weakDataFetch=getFetch;
    [weakDataFetch beginLeadTaskWithCallbackBlock:^(NSArray *mm){



        dispatch_async(dispatch_get_main_queue(), ^{

        //update main UI 

        });

    }];


文章来源: How to return the ouput if method is using NSURLConnection Asynchronous calls with blocks