我可以从网站下载图片并将其永久保存在我的应用程序中吗?我真的不知道,但它会成为我的应用程序的一个很好的功能。
发布于 2011-06-05 01:11:59
发布于 2011-06-05 01:14:27
这是主要的概念。玩得开心;)
NSURL *url = [NSURL URLWithString:@"http://example.com/yourImage.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [path stringByAppendingString:@"/yourLocalImage.png"];
[data writeToFile:path atomically:YES];
发布于 2015-05-13 18:27:25
正如其他人所说,在许多情况下,您应该在后台线程中下载图片,而不会阻塞用户界面
在这种情况下,我最喜欢的解决方案是使用块的方便方法,就像这样:(credit -> iOS: How To Download Images Asynchronously (And Make Your UITableView Scroll Fast))
- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ( !error )
{
UIImage *image = [[UIImage alloc] initWithData:data];
completionBlock(YES,image);
} else{
completionBlock(NO,nil);
}
}];
}
并将其命名为
NSURL *imageUrl = //...
[[MyUtilManager sharedInstance] downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) {
//Here you can save the image permanently, update UI and do what you want...
}];
https://stackoverflow.com/questions/6238139
复制相似问题