demo code:
+(void)downloadImageWithUrl:(NSString*)showImageUrl completed:(void(^)(NSString* __nullable result))callback
{
if(showImageUrl && ![showImageUrl isEqualToString:@""]){
NSURLSessionConfiguration *configuration =[NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager =[[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
NSURL *URL =[NSURL URLWithString:showImageUrl];
NSURLRequest *request =[NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask =[manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath,NSURLResponse *response){
NSURL *documentsDirectoryURL =[[NSFileManager defaultManager]URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return[documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response,NSURL *filePath,NSError *error){
if(!error){
callback(filePath.path);//save the path
}
else{
callback(nil);
}
}];
[downloadTask resume];
}
}
以上的filePath记录下它的完整路径,在下次重启后调用下面命令总返回false
[[NSFileManager defaultManager]fileExistsAtPath:filePath];
要检测之前下载的文件,必须重组整个路径,因为app重启后,之前下载下来的文件的整个路径也变化了。
可以用下面方式去重组路径。
-(NSString*)filePath
{
NSURL *url =[[NSFileManager defaultManager]URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
url =[url URLByAppendingPathComponent:[_filePath lastPathComponent]];
return url.path;
}
网友评论