【问题标题】:download image from web with progress to photos app AFNetworking 3从网络下载图像到照片应用程序 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]]]];

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

【问题讨论】:

标签: ios objective-c progress afnetworking-3


【解决方案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];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多