从网络下载图像到照片应用程序 AFNetworking 3

Posted

技术标签:

【中文标题】从网络下载图像到照片应用程序 AFNetworking 3【英文标题】:download image from web with progress to photos app AFNetworking 3 【发布时间】:2016-03-03 07:34:22 【问题描述】:

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

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 有一种方法可以在 imageview 中显示图像,例如

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

但是有没有类似的方法来下载图片?

【问题讨论】:

这只是一个下载,没有特定的图像...... 只是照片应用的普通 jpeg 你可以使用这个方法cocoadocs.org/docsets/AFNetworking/3.0.0-beta.1/Classes/…: 但是一个问题是,AFNetworking 3.X 需要 xcode 7 并且它仍处于测试阶段。 你应该使用github.com/rs/SDWebImage。简单且最适合带进度的图像下载 【参考方案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];

【讨论】:

【参考方案2】:

这样做。

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

【讨论】:

这看起来像是 osx 下载的示例,我想将图像保存到 iphone 或 ipad 上的照片应用程序【参考方案3】:

我最近也遇到过同样的情况。 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来获取下载进度。

【讨论】:

【参考方案4】:

您可以使用AFHTTPRequestOperation。将responseSerializer 设置为AFImageResponseSerializer。要获得进度,只需使用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];

【讨论】:

以上是关于从网络下载图像到照片应用程序 AFNetworking 3的主要内容,如果未能解决你的问题,请参考以下文章

Cordova - 将图像从 url 保存到设备照片库中

Alamofire - 使用照片时图像上传失败

如何将图像从安卓相机上传到网络服务器(不在应用程序中)

IOS如何防止下载的图片以编程方式缓存

用于移动safari的html5网络应用程序,用于从Photos.app上传图像?

在 iOS 设备中保存从 Web 下载的图像的最佳位置?