iOS:从网址下载图片并保存在设备中 [英] iOS: Download image from url and save in device
问题描述
我尝试从网址下载图片 http://a3.twimg .com / profile_images / 414797877 / 05052008321_bigger.jpg
I am trying to download the image from the url http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg
我使用以下代码,但图片未保存在设备中。我想知道我做错了什么。
I am using the following code, but image is not saved in the device. I want to know what I am doing wrong.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"pkm.jpg"];
NSData *thedata = NULL;
[thedata writeToFile:localFilePath atomically:YES];
UIImage *img = [[UIImage alloc] initWithData:thedata];
推荐答案
如果设置 / code>到
nil
,你期望它写入磁盘是什么?
If you set theData
to nil
, what do you expect it to write to the disk?
可以使用 NSData * theData = [NSData dataWithContentsOfURL:yourURLHere];
从磁盘加载数据,然后使用 writeToFile:atomically: / code>。如果您需要更多控制加载进程或在后台进行,请查看
NSURLConnection
及相关指南的文档。
What you can use is NSData* theData = [NSData dataWithContentsOfURL:yourURLHere];
to load the data from the disk and then save it using writeToFile:atomically:
. If you need more control over the loading process or have it in background, look at the documentation of NSURLConnection
and the associated guide.
这篇关于iOS:从网址下载图片并保存在设备中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!