//下载图片
/*
NSData *data = [[NSData alloc]initWithContentsOfURL:imageUrl];
NSLog(@"%@",data);
UIImage *image = [[UIImage alloc]initWithData:data];
imageview.image = image;
*/
//方式2使用NSURLsession 请求图片
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:imageUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error || !data) {
return ;
}
UIImage *image = [[UIImage alloc]initWithData:data];
imageview.image = image;
}];
//执行网络请求
[dataTask resume];
*/
//方式3 使用NSURLConnection请求图片
//创建NSURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:imageUrl];
//使用异步请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError || !data) {
return ;
}
UIImage *image = [[UIImage alloc]initWithData:data];
imageview.image = image;
}];
//创建url
//方式1
/*
NSData *data = [[NSData alloc]initWithContentsOfURL:imageUrl];
NSLog(@"%@",data);
UIImage *image = [[UIImage alloc]initWithData:data];
imageview.image = image;
*/
//方式2使用NSURLsession 请求图片
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:imageUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error || !data) {
return ;
}
UIImage *image = [[UIImage alloc]initWithData:data];
imageview.image = image;
}];
//执行网络请求
[dataTask resume];
*/
//方式3 使用NSURLConnection请求图片
//创建NSURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:imageUrl];
//使用异步请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError || !data) {
return ;
}
UIImage *image = [[UIImage alloc]initWithData:data];
imageview.image = image;
}];
本文详细介绍了三种方法:直接使用NSURL加载图片、通过NSURLSession进行异步请求、使用NSURLConnection进行异步请求,来从网络下载并展示图片。重点在于优化加载速度和用户体验。
466

被折叠的 条评论
为什么被折叠?



