我有一个应用程序从服务器下载一组照片。我正在使用异步请求,因为我不希望UI被阻止。但是,我发现请求非常缓慢并且需要很长时间才能加载。异步请求运行缓慢 - iOS
我知道你可以将队列类型设置为[NSOperationQueue mainQueue]
,但这只是将异步请求放回到主线程上,这首先使异步请求失败。
有没有办法加速请求或告诉iOS:“在后台运行此请求,但尽快执行,不要将其保留到队列末尾”???
这里是我的代码:
// Set up the photo request.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:PHOTO_URL, pass_venue_ID, PHOTO_CLIENT_ID, PHOTO_CLIENT_SECRET]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// Begin the asynchromous image loading.
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error == nil) {
// Convert the response data to JSON.
NSError *my_error = nil;
NSDictionary *feed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&my_error];
// Check to see if any images exist
// for this particular place.
int images_check = [[NSString stringWithFormat:@"%@", [[[feed objectForKey:@"response"] valueForKey:@"photos"] valueForKey:@"count"]] intValue];
if (images_check > 0) {
// Download all the image link properties.
images_prefix = [[[[feed objectForKey:@"response"] valueForKey:@"photos"] valueForKey:@"items"] valueForKey:@"prefix"];
images_suffix = [[[[feed objectForKey:@"response"] valueForKey:@"photos"] valueForKey:@"items"] valueForKey:@"suffix"];
images_width = [[[[feed objectForKey:@"response"] valueForKey:@"photos"] valueForKey:@"items"] valueForKey:@"width"];
images_height = [[[[feed objectForKey:@"response"] valueForKey:@"photos"] valueForKey:@"items"] valueForKey:@"height"];
// Set the image number label.
number_label.text = [NSString stringWithFormat:@"1/%lu", (unsigned long)[images_prefix count]];
// Download up to 5 images.
images_downloaded = [[NSMutableArray alloc] init];
// Set the download limit.
loop_max = 0;
if ([images_prefix count] > 5) {
loop_max = 5;
}
else {
loop_max = [images_prefix count];
}
for (NSUInteger loop = 0; loop < loop_max; loop++) {
// Create the image URL.
NSString *image_URL = [NSString stringWithFormat:@"%@%@x%@%@", images_prefix[loop], images_width[loop], images_height[loop], images_suffix[loop]];
// Download the image file.
NSData *image_data = [NSData dataWithContentsOfURL:[NSURL URLWithString:image_URL]];
// Store the image data in the array.
[images_downloaded addObject:image_data];
}
// Load the first image.
[self load_image:image_num];
}
else if (images_check <= 0) {
// error...
}
}
else {
// error
}
}];
感谢您的时间,丹。
检查网络连接,尝试ping主机 –