iOS:从 url 下载图像并保存在设备中 [英] iOS: Download image from url and save in device
问题描述
我正在尝试从 url 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];
推荐答案
如果您将 theData
设置为 nil
,您希望它写入磁盘的内容是什么?
If you set theData
to nil
, what do you expect it to write to the disk?
您可以使用NSData* theData = [NSData dataWithContentsOfURL:yourURLHere];
从磁盘加载数据,然后使用writeToFile:atomically:
保存它.如果您需要更多地控制加载过程或将其置于后台,请查看 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:从 url 下载图像并保存在设备中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!