Ios JSON异步请求

Ios JSON异步请求,ios,iphone,json,Ios,Iphone,Json,我想使用async req来获取json数据,我已经通过syncrouns完成了这项工作,但现在需求发生了变化,但我无法将此代码修改为aync,因为我必须返回NSdata + (NSString *)stringWithUrl:(NSURL *)url { // if(kShowLog) NSLog(@"%@", url); NSURL *newURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@"

我想使用async req来获取json数据,我已经通过syncrouns完成了这项工作,但现在需求发生了变化,但我无法将此代码修改为aync,因为我必须返回NSdata

+ (NSString *)stringWithUrl:(NSURL *)url
{

//    if(kShowLog)
        NSLog(@"%@", url);

    NSURL *newURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",url]];

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:newURL
                                                cachePolicy:NSURLRequestReloadIgnoringCacheData
                                            timeoutInterval:1];
    // Fetch the JSON response
    NSData *urlData;
    NSURLResponse *response;
    NSError *error;
//    NSOperationQueue *opQueue;

    // Make synchronous request
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
    return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}

那么异步电机有什么问题

     NSString *responseString;
     NSOperationQueue *operation = [[NSOperationQueue alloc]init];
       [NSURLConnection sendAsynchronousRequest:request queue:operation completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
           NSLog(@"data %@", data);
        responseString = [[NSString alloc] initWithData:Data encoding:NSUTF8StringEncoding];
       }];
     return responseString;

在2上调用stringWithUrl。如果要继续返回数据,请执行线程。(我选择异步数据

dispatch_async(dispatch_get_global_queue(), ^{
     NSData *d = [self stringWithUrl:myURL];
     ...

     //update ui
     dispatch_sync(dispatch_get_main_queue(), ^{
         ...
     });
});

一种可行的方法是,在等待时运行runloop,这是一种相当麻烦的方法(苹果一直在mac上使用较旧的API):

hackisch::但是如果完成块在同一个线程上运行,那么就同步包装async

    __block NSString *responseString = nil;
   [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:myurl] 
                                      queue:[NSOperationQueue mainQueue] 
                          completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    responseString = [[NSString alloc] initWithData:Data encoding:NSUTF8StringEncoding];
    if(!responseString) {
         responseString = @"";
    }
   }];

   while(!responseString) { 
       [NSRunloop currentRunloop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1];
   }

   return responseString;

您必须为此进程创建一个单独的线程,获取json数据的同步调用将阻塞主线程

我将您的代码更改为执行异步操作,以便从web服务获取json数据

+ (void)stringWithUrl:(NSURL *)url
{

 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
 dispatch_async(queue, ^{

    //    if(kShowLog)
    NSLog(@"%@", url);

    NSURL *newURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",url]];

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:newURL
                                                cachePolicy:NSURLRequestReloadIgnoringCacheData
                                            timeoutInterval:1];
    // Fetch the JSON response
    NSData *urlData;
    NSURLResponse *response;
    NSError *error;
    //    NSOperationQueue *opQueue;

    // Make synchronous request
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

    dispatch_sync(dispatch_get_main_queue(), ^{

        //Here you have to put your code, which you wanted to get executed after your data successfully retrived.
        //This block will get executed after your request data load to urlData.
    });

 });

}

为什么不尝试使用?您有两个相互冲突的要求:您应该返回作为操作结果的NSString对象,并且您的方法应该是异步的。这是不可能的。调用方无法立即获得异步方法的结果。请修复您的要求。请尝试我的解决方案@user3355452您如何返回任何内容若要返回类型void?????为什么要向上投票?您的ans不正确。PLZZZHOUT return在此执行;)此外,您还错过了\uuuu块。您必须注意,此处未以同步方式向thread0提供NSData。。。这就是异步的要点;)写内联和hackisch,但这将异步执行请求,并等待(不阻塞)dateWithTimeIntervalFromNow not found类方法。我说我键入了内联。我想你可以在医生那里待上30年。。方法是
dateWithTimeIntervalSinceNow
:)