2015-06-17 114 views
0

我有一个应用程序从服务器下载一组照片。我正在使用异步请求,因为我不希望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 
     } 
    }]; 

感谢您的时间,丹。

+0

检查网络连接,尝试ping主机 –

回答

2

我认为你的问题的心不是请求运行缓慢,它的你是不是在主线程更新UI元素,围绕任何用户界面更新(比如设置在标签上的文字)作为的Fonix表示,与

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

好的谢谢。我会试试这个,让你知道。 – Supertecnoboff

+2

终于有一些时间来尝试这一点,我必须说,它的作品完美!!!!!非常感谢你:) – Supertecnoboff

0

它不是响应速度慢的iOS,但dataWithContentsOfURL在后台线程中不起作用。苹果公司的建议是,你应该代表 异步使用NSURLConnection的 - didReceiveResponse - didReceiveData

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:_mAuthenticationTimeoutInterval]; 

在这些方法中,你可以使用数据块为好。

如果你真的希望这些多次下载速度更快,你应该使用NSOperationQueue并行下载。你可以参考enter link description here

0

我认为一个好的解决办法是使用AFNetworking时的NSOperation相结合,检查这个代码我写的做多一个操作异步

NSMutableArray *operations = [[NSMutableArray alloc] init]; 
for(NSObject *obj in caches) { 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL:url];   
//...set up your mutable request options here 

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    operation.responseSerializer = [AFJSONResponseSerializer serializer]; 
    operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"]; 
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 

     NSInteger statusCode = operation.response.statusCode; 
     if(statusCode==200) { 
     } 

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"API Call error:%@", error.localizedDescription); 
    }]; 

    [[requestManager operationQueue] addOperation:operation]; 
    [operations addObject:operation]; 

    if([operations count] >= MAX_API_CALL) break; 
} 

[AFHTTPRequestOperation batchOfRequestOperations:operations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) { 
} completionBlock:^(NSArray *operations) { 

    NSError *error; 
    for (AFHTTPRequestOperation *op in operations) { 
     if (op.isCancelled){ 
     } 
     if (op.responseObject){ 
      // process your responce here 
     } 
     if (op.error){ 
      error = op.error; 
     } 
    } 
}]; 
+0

@Supertecnoboff AFNetworking最后更新是18天前,它支持Swift,https://github.com/AFNetworking/AFNetworking – loretoparisi