我想使用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];
}
答案 0 :(得分:0)
dispatch_async(dispatch_get_global_queue(), ^{
NSData *d = [self stringWithUrl:myURL];
...
//update ui
dispatch_sync(dispatch_get_main_queue(), ^{
...
});
});
答案 1 :(得分:0)
一种方法可行但是QUITE the hack(苹果公司一直在mac上使用旧苹果)将在等待时运行runloop:
hackisch ::但是如果完成块在同一个线程上运行,那么同步包装异步,那么runloop
__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;
答案 2 :(得分:0)
您必须为此进程创建一个单独的线程,获取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.
});
});
}
答案 3 :(得分:-1)
Asynchronous当时有什么问题,
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;