第一种:直接赋值
-(void)post
{
NSURL *url = [NSURL URLWithString:@"http://......."];
NSData *data = [NSData dataWithContentsOfURL:url];
self.imageView.image = [UIImage imageWithData:data];
}
第二种:发送异步请求
-(void)second
{
NSURL *url = [NSURL URLWithString:@"http://......."];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
self.imageView.image = [UIImage imageWithData:data];
}];
}
第三种:NSURLConnection代理
-(void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://......."];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.dataM = [NSMutableData data];
self.totoleLength = response.expectedContentLength;
NSLog(@"%s",__func__);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.dataM appendData:data];
self.currentLength = self.dataM.length;
CGFloat progress = 1.0 * self.currentLength / self.totoleLength;
NSLog(@"%f",progress);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%s",__func__);
NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *fullPath = [cache stringByAppendingPathComponent:@"abc.png"];
[self.dataM writeToFile:fullPath atomically:YES];
}