IOS如何从URL下载图像[重复]

时间:2022-03-25 03:41:06

This question already has an answer here:

这个问题在这里已有答案:

I have a URL image on the server. I use this to save avatar. How to I can use URL to download image and set in my ImageView.

我在服务器上有一个URL图像。我用它来保存头像。如何使用URL下载图像并在我的ImageView中设置。

2 个解决方案

#1


try to use this code to download image in background

尝试使用此代码在后台下载图像

Make sure your url contains a image and it is valid url

确保您的网址包含图片,并且该网址是有效的网址

NSString *strImgURLAsString = @"imageURL";
[strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *imgURL = [NSURL URLWithString:strImgURLAsString];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (!connectionError) {
        UIImage *img = [[UIImage alloc] initWithData:data];
        // pass the img to your imageview
    }else{
        NSLog(@"%@",connectionError);
    }
}];

#2


You can try this code

您可以尝试此代码

NSData *imageData = [NSData dataWithContentsOfURL:myImageURL];
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];

#1


try to use this code to download image in background

尝试使用此代码在后台下载图像

Make sure your url contains a image and it is valid url

确保您的网址包含图片,并且该网址是有效的网址

NSString *strImgURLAsString = @"imageURL";
[strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *imgURL = [NSURL URLWithString:strImgURLAsString];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (!connectionError) {
        UIImage *img = [[UIImage alloc] initWithData:data];
        // pass the img to your imageview
    }else{
        NSLog(@"%@",connectionError);
    }
}];

#2


You can try this code

您可以尝试此代码

NSData *imageData = [NSData dataWithContentsOfURL:myImageURL];
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];