如何在情节提要中使用 NSURLConnection 下载文件
Posted
技术标签:
【中文标题】如何在情节提要中使用 NSURLConnection 下载文件【英文标题】:how download file with NSURLConnection in storyboard 【发布时间】:2013-05-09 05:02:49 【问题描述】:我是NSURLConnection
的菜鸟。我搜索了谷歌并找到了这个网站,但我不明白。
请朋友们解释一下我从文档文件夹中的url下载的代码。
这是我的代码:
- (void)viewDidLoad
[super viewDidLoad];
NSURL *url =[NSURL URLWithString:@"http://cdn.arstechnica.net/wp-content/uploads/2012/09/iphone5-intro.jpg"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *con = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[con start];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
//I dont know what thing put here
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
//I dont know what thing put here
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
//I dont know what thing put here
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"The Connection has been LOST" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
【问题讨论】:
参考苹果文档:developer.apple.com/library/mac/#documentation/Cocoa/Reference/… 【参考方案1】:使用 NSURLConnection ,试试这个
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cdn.cultofmac.com/wp-content/uploads/2013/03/colorware-iphone-5-xl.jpg"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection)
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [[NSMutableData data] retain];
else
// Inform the user that the connection failed.
有关 NSURLConnection 的更多信息,请参阅:URL Loading System Programming Guide
编辑
这里recievedData
是NSMutableData
类型的实例变量
-(void)downloadWithNsurlconnection
NSURL *url = [NSURL URLWithString:currentURL];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
receivedData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[receivedData setLength:0];
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
[receivedData appendData:data];
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[currentURL stringByAppendingString:@".jpg"]];
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[receivedData writeToFile:pdfPath atomically:YES];
【讨论】:
编辑了我的答案,检查一下 我的朋友如果我想在点击按钮开始下载文件时必须在按钮 Action 中调用 downloadWithNsurlconnection 方法? 在按钮上单击调用方法downloadWithNsurlconnection,它将开始下载 那么它在 connectionDidFinishLoading 中做了什么?你检查代码了吗?它将数据保存在 writeTofile 方法指定的路径中【参考方案2】:最好使用带有块的 NSURLConnection 异步执行此操作。
- (NSString *)documentsDirectoryPath
NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
return directories[0];
- (void)downloadImage
NSString *urlPath = @"http://cdn.arstechnica.net/wp-content/uploads/2012/09/iphone5-intro.jpg";
NSURL *url = [NSURL URLWithString:urlPath];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response, NSData *responseData, NSError *error)
if (responseData)
NSString *imageName = [urlPath lastPathComponent];
NSString *imagePath = [[self documentsDirectoryPath]stringByAppendingPathComponent:imageName];
[responseData writeToFile:imagePath atomically:YES];
];
【讨论】:
【参考方案3】:不使用NSURLConnection
,您可以轻松下载文件,无需额外调用委托。试试这个。
NSString *url = @"http://cdn.cultofmac.com/wp-content/uploads/2013/03/colorware-iphone-5-xl.jpg";
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdirectory = [path objectAtIndex:0];
NSString *dataPath = [documentdirectory stringByAppendingPathComponent:@"Pictures"];
NSString *localFileURL = [NSString stringWithFormat:@"%@/%@",dataPath,[url lastPathComponent]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
if([data writeToFile:localFileURL atomically:YES])
NSLog(@"Downloaded File");
【讨论】:
我认识我的朋友,但我想用 NSURLConection 下载文件...你能帮帮我吗? @david 请看这个***.com/questions/3464252/… "但是一般来说,NSData 的 dataWithContentsOfURL 应该只用于访问本地文件资源。" ***.com/a/21961737/505093以上是关于如何在情节提要中使用 NSURLConnection 下载文件的主要内容,如果未能解决你的问题,请参考以下文章
使用情节提要时如何在appDelegate中获取指向viewController的指针