1

我正在尝试将带有进度的图像从网络服务器直接保存到照片应用程序。这是我目前使用的没有进展:

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];

我知道我可以使用NSURLSessionDownloadDelegate来获取下载进度,但我想AFNetworking用于下载图像并在下载时获取进度。我知道 AFNetworking 有一种在图像视图中显示图像的方法,例如

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

但是有没有一种类似的方法来下载图像?

4

4 回答 4

1

尝试这个 :-

 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];
于 2016-03-03T09:43:58.493 回答
0

您可以使用AFHTTPRequestOperation. 设置responseSerializerAFImageResponseSerializer。要获得进度,只需使用setDownloadProgressBlock. 下面是一个例子。

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];
于 2016-03-03T09:33:59.813 回答
0

这样做。

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];
于 2016-03-03T08:13:33.873 回答
0

我最近遇到了同样的情况。
NSProgress 对象不是你自己创建的,它是由 AFNetworking 自动创建的。

- (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);
}

}

您需要使用 KVO 来获取下载进度。

于 2016-03-03T09:17:37.613 回答