简体   繁体   中英

download image from web with progress to photos app AFNetworking 3

I am trying to save an image with progress from a webserver directly to the Photos app. this is what i use at the moment without progress:

NSURLSessionDownloadTask *dl = [[NSURLSession sharedSession]
                                    downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
                                            if ( !error )
                                            {
                                                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
                                                completionBlock(YES,image);
                                            } else{
                                                completionBlock(NO,nil);
                                            }

                                        }
                                    ];  
    [dl resume];

I know I could use the NSURLSessionDownloadDelegate to get the progress of the download but i want to use AFNetworking for downloading the image and get the progress while downloading. I know AFNetworking has a method to display images in an imageview like

[postCell.iv_postImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",[[Utilities sharedUtilities] basePath],[item.imagePath substringFromIndex:2]]]];

but is there a simular method to just download the image?

Try this :-

 NSURLSessionConfiguration *configuration =[NSURLSessionConfiguration defaultSessionConfiguration];
 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

 NSURL *URL = your_url_here;
 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) {
    NSLog(@"File downloaded to: %@", filePath);

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    [library writeVideoAtPathToSavedPhotosAlbum:URL completionBlock:^(NSURL *assetURL, NSError *error) {

        if (error) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error in Downloading video "message:[error localizedDescription]                                                               delegate:nil cancelButtonTitle:@"Ok"otherButtonTitles:nil];
            [alertView show];

        } else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Downloading video success....!!!"message:[error localizedDescription]delegate:nil cancelButtonTitle:@"Ok"otherButtonTitles:nil];
            [alertView show];
        }

    }];

}];

[downloadTask resume];

Do like this.

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/image.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request
                                                                 progress:^(NSProgress * _Nonnull downloadProgress){  /* update your progress view  */ }
                                                              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)
                                                                            {
                                                                                NSLog(@"File downloaded to: %@", filePath);
                                                                            }];
[downloadTask resume];

I have meet the same case recently.
The NSProgress object is not created by yourself,it is created by AFNetworking automatically.

- (void)startDownload {
NSString *downloadUrl = @"http://....";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:downloadUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
[request setHTTPMethod:@"GET"];

NSProgress *progress = nil;
NSURL *filePathUrl = [NSURL fileURLWithPath:_filePath];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *SessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURLSessionDownloadTask *downloadTask = [SessionManager downloadTaskWithRequest:request progress:&progress destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

    //here return the destination of the downloaded file
    return filePathUrl;

} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

    if (error) {
        NSLog(@"download failure %@",error);
    }
    else {
        NSLog(@"mission succeed");

    }

}];
self.progress = progress;
// add the key observer to get the progress when image is downloading
[self.progress addObserver:self
                forKeyPath:@"fractionCompleted"
                   options:NSKeyValueObservingOptionNew
                   context:NULL];

[downloadTask resume];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{

if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {

    __weak typeof(self) weakSelf = self;
    NSProgress *progress = (NSProgress *)object;
    NSLog(@"progress= %f", _tag, progress.fractionCompleted);
}

}

You need to use the KVO to get the progress of the downloading.

You can use the AFHTTPRequestOperation . Set the responseSerializer to AFImageResponseSerializer . To get the progress, simply use the setDownloadProgressBlock . Below is an example.

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];

requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    UIImage *result = (UIImage *)responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[requestOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

}];

[requestOperation start];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM