IOS如何从URL下载图像

2 objective-c uiimageview ios

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

Mal*_*oni 8

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

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

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);
    }
}];
Run Code Online (Sandbox Code Playgroud)