2012-04-17 238 views
5

我想用较短的超时下载,以便速度更快,并防止应用程序崩溃而导致连接不良。如何设置dataWithContentsOfURL的超时时间:url

- (void) CreateTitleView { 
    NSURL* url; 
    NSData* imageData; 
    imageData = [NSData dataWithContentsOfURL:url ]; 
    UIImage* image = [UIImage imageWithData:imageData]; 
} 

我不擅长目标C,所以我请求你的帮助,这样做。谢谢。

+0

短超时不会使您的连接更快!但看看NSURLConnection。 – 2012-04-17 19:43:48

回答

2

您无法通过设置超时来控制下载速度。这只会控制你的应用程序在放弃下载之前等待的时间。您应该重构应用程序以在后台加载图像数据,以便UI保持响应,直到下载完成。

检出NSURLConnection(sendAsynchronousRequest)或AFNetworking

+1

好的。我知道较短的超时不会导致下载速度更快。如何从无法访问的网址下载,设置超时至少可以避免不必要的下载。那么如何在'[NSData dataWithContentsOfURL:url]'上设置超时? – Yeung 2013-03-06 04:37:16

+0

@Yeung - 你不能afaik。如果您需要能够控制从URL检索数据的超时设置,请使用['NSURLConnection'](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference改为class /代替/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html)。 – Perception 2013-03-06 06:35:46

9

这几天,这是可能的。该API是这样的:

NSURLResponse* urlResponse; 
NSError* error; 
NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20]; 
NSData* d = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&urlResponse error:&error];