使用NSURLSessionDownloadTask

时间:2017-11-30 09:58:15

标签: ios objective-c nsurlrequest nsurlsessiondownloadtask

我正在开发一个我想下载某些文件的应用程序。

  1. 如果要下载的文件是图片,我只需下载
  2. 如果要下载的文件是视频,我需要触发另一个缩略图下载
  3. 为此,我使用的是NSURLSessionDownloadTask。使用图像一切正常但是当涉及到视频时,视频本身会正确下载,但是thumbanil总是会返回错误:

      

    错误:网址不兼容

    以下是代码:

    - (void)download:(Message)message
                   completion:(void (^)(NSArray *))completion {
    
    NSString *mediaURL = [NSString stringWithUTF8String: message.remoteMediaUrl()];
    
    __block BOOL isVideo = NO;
    NSString* mimeType = [NSString stringWithUTF8String:message.mediaMimeType()];
    if ([mimeType hasPrefix:@"video/"])
        isVideo = YES;
    
    NSString *mediaName = [mediaURL lastPathComponent];
    NSURL *URL = [NSURL URLWithString:mediaURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSString *user = [self.user];
    NSString *password = [self.password];
    
    [self.manager setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLAuthenticationChallenge * _Nonnull challenge, NSURLCredential *__autoreleasing  _Nullable * _Nullable credential) {
        NSString *authenicationMethod = challenge.protectionSpace.authenticationMethod;
        if ([authenicationMethod isEqualToString:NSURLAuthenticationMethodHTTPDigest]) {
            *credential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceForSession];
            return NSURLSessionAuthChallengeUseCredential;
        }
        return NSURLSessionAuthChallengeCancelAuthenticationChallenge;
    }];
    
    NSURLSessionDownloadTask *downloadTask = [self.manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    
        NSURL *fileURL = [[ContentService imageDownloadDirectoryURL] URLByAppendingPathComponent: mediaName];
        [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
    
        fileURL = [fileURL URLByAppendingPathExtension:[self getExtensionFromMimeType:message.mediaMimeType()]];
        return fileURL;
    } completionHandler:^(NSURLResponse *response, NSURL *fileURL, NSError *error) {
        if (error != nil) {
            NSLog(@"Error: %@", [error localizedDescription]);
            completion(nil);
        } else {
            NSLog(@"File downloaded to: %@ ", fileURL);
        ////////////////////////////////////////////////
            if (isVideo) {
                NSLog(@"Download thumbnail for video");
                isVideo = NO;
                NSString *thumbnailURLAsString = [NSString stringWithUTF8String: message.remoteThumbnailUrl()];
                NSString *thumbnailName = [thumbnailURLAsString lastPathComponent];
                NSURL *thumbnailURL = [NSURL URLWithString:thumbnailName];
    
                NSURLRequest *thumbnailRequest = [NSURLRequest requestWithURL:thumbnailURL];
                NSURLSessionDownloadTask *thDownloadTask = [self.manager downloadTaskWithRequest:thumbnailRequest progress:nil destination:^NSURL *(NSURL *targetPath2, NSURLResponse *thresponse) {
    
                    NSURL *thumbnailfileURL = [[ContentService imageDownloadDirectoryURL] URLByAppendingPathComponent: thumbnailName];
                    [[NSFileManager defaultManager] removeItemAtURL:thumbnailfileURL error:nil];
                    return thumbnailfileURL;
                } completionHandler:^(NSURLResponse *thresponse, NSURL *thumbnailfileURL, NSError *error) {
                    if (error != nil) {
                        NSLog(@"Error: %@", [error localizedDescription]);
                        completion(nil);
                    } else {
                        NSLog(@"File downloaded to: %@", thumbnailfileURL);
                        completion([NSArray arrayWithObjects:fileURL, thumbnailfileURL,nil]);
                    }
                }];
                [thDownloadTask resume];
            } // if isVideo 
           //////////////////////////
            else {
                completion([NSArray arrayWithObjects:fileURL, nil]);
            }
        }
    }];
    [downloadTask resume];
    

    }

    我知道代码会重复,但是现在我想要有一些工作。 有人能告诉我出了什么问题吗?

    此外,如果这种方法不正确,我应该使用哪一种?

    提前致谢并问候

0 个答案:

没有答案