How to return the ouput if method is using NSURLConnection Asynchronous calls with blocks

本小妞迷上赌 提交于 2019-12-11 14:50:12

问题


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

回答1:


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.

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



回答2:


There is no way. Connection result is not known when app calls return statement. You should use something like

[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];

         }
         ];



回答3:


It should be like this

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

     }
     ];
}



回答4:


your DataFetchController.h file

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

your DataFetchController.m file

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

         }

     }];

}

block call your view controller

weak use for avoid memory leaks

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



        dispatch_async(dispatch_get_main_queue(), ^{

        //update main UI 

        });

    }];


来源:https://stackoverflow.com/questions/22473077/how-to-return-the-ouput-if-method-is-using-nsurlconnection-asynchronous-calls-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!