gpt4 book ai didi

ios - 异步请求运行缓慢 - iOS

转载 作者:行者123 更新时间:2023-11-28 21:44:16 24 4
gpt4 key购买 nike

我有一个应用程序可以从服务器下载一组照片。我正在使用异步请求,因为我不想阻止 UI。但是,我发现请求非常慢并且需要很长时间才能加载。

我知道您可以将队列类型设置为 [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
}
}];

谢谢你抽出时间,丹。

最佳答案

我认为你的问题不是请求运行缓慢,而是你正在更新不在主线程上的 UI 元素,围绕任何 UI 更新(比如在标签上设置文本)

dispatch_sync(dispatch_get_main_queue(), ^{
<#code#>
});

关于ios - 异步请求运行缓慢 - iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30884081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com