点击按钮开始下载
- (IBAction)onClick:(id)sender { NSMutableDictionary *imageDic = [[NSMutableDictionary alloc] init]; //获取本地沙箱的缓存路径 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachesDirectory = paths[0]; NSString *downloadPath = [cachesDirectory stringByAppendingPathComponent:@"test1.jpg"]; //先从本地获取缓存图片 UIImage *image = [UIImage imageWithContentsOfFile:downloadPath]; //如果从本地缓存中获取为空,那么再从应用资源中获取一次 if (image == nil) { image = [UIImage imageNamed:@"test1.jpg"]; } if (nil != image) { [imageDic setObject:image forKey:@"image"]; NSLog(@"缓存有图片!"); _imageView1.image = image; } //如果本地缓存图片为空,则远程请求,并缓存到本地 if(image == nil) { NSString *path = [[NSString alloc] initWithFormat:@"/service/download.php?email=%@&FileName=test1.jpg",@"gs.654586026@qq.com"]; path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"51work6.com" customHeaderFields:nil]; MKNetworkOperation *downloadOperation = [engine operationWithPath:path params:nil httpMethod:@"POST"]; [downloadOperation addDownloadStream:[NSOutputStream outputStreamToFileAtPath:downloadPath append:TRUE]]; [downloadOperation onDownloadProgressChanged:^(double progress) { NSLog(@"download progress: %.2f%%", progress*100.0); _progressView.progress = progress; }]; [downloadOperation addCompletionHandler:^(MKNetworkOperation *operation) { NSLog(@"download file finished!"); UIImage *image = [UIImage imageWithContentsOfFile:downloadPath]; _imageView1.image = image; } errorHandler:^(MKNetworkOperation *errorOp, NSError* err) { NSLog(@"MKNetwork请求错误 : %@", [err localizedDescription]); }]; [engine enqueueOperation:downloadOperation]; }}