如何将视频上传到亚马逊s3作为v2.1版本iOS上的多部分视频上传



如何将视频作为多部分上传方法上传到amazons3。如果有人知道或有一些想法如何解决这个问题,请给我一些建议。

非常感谢您抽出时间!

首先使用URLSession创建AWS对象&用委托方法处理

- (void)initBackgroundURLSessionAndAWS:(NSString*)MediaId
{
    VideoId= MediaId;
   AWSStaticCredentialsProvider *credentialsProvider = [AWSStaticCredentialsProvider credentialsWithAccessKey:<Your Access Key> secretKey:<Your Secret Key>];
    AWSServiceConfiguration *configuration = [AWSServiceConfiguration configurationWithRegion:AWSRegionUSEast1 credentialsProvider:credentialsProvider];
    NSURLSessionConfiguration *URLconfiguration;

if ([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] == NSOrderedAscending) {
    // iOS7 or earlier
    URLconfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:MediaId];
} else {
    // iOS8 or later
    URLconfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:MediaId];
}

    self.urlSession = [NSURLSession sessionWithConfiguration:URLconfiguration delegate:self delegateQueue:nil];
    [AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;
    self.awss3 = [[AWSS3 alloc] initWithConfiguration:configuration];
    NSURL *movieURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] valueForKey:@"mediaURL"]];

    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"Video.MOV"];
    NSData *imageData = [NSData dataWithContentsOfURL:movieURL];
    [imageData writeToFile:path atomically:YES];
    NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
    AWSS3GetPreSignedURLRequest *getPreSignedURLRequest = [AWSS3GetPreSignedURLRequest new];
    getPreSignedURLRequest.bucket = <Bucket ID>;
    getPreSignedURLRequest.key = [NSString stringWithFormat:@"%@.MOV",MediaId];
    getPreSignedURLRequest.HTTPMethod = AWSHTTPMethodPUT;
    getPreSignedURLRequest.expires = [NSDate dateWithTimeIntervalSinceNow:3600];
    //Important: must set contentType for PUT request
    getPreSignedURLRequest.contentType = @"movie/mov";
    [[[AWSS3PreSignedURLBuilder defaultS3PreSignedURLBuilder] getPreSignedURL:getPreSignedURLRequest] continueWithBlock:^id(BFTask *task) {
            if (task.error)
            {
                NSLog(@"Error BFTask: %@", task.error);
                [self showError];
            }
            else
            {
               // [SVProgressHUD dismiss];
                NSURL *presignedURL = task.result;
                NSLog(@"upload presignedURL is: n%@", presignedURL);
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:presignedURL];
            request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
            [request setHTTPMethod:@"PUT"];
            [request setValue:@"movie/mov" forHTTPHeaderField:@"Content-Type"];
            NSURLSessionUploadTask *uploadTask = [self.urlSession uploadTaskWithRequest:request fromFile:url];
            [uploadTask resume];
        }
        return nil;
    }];
}
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
        // Upload progress
        NSLog(@"Progress : %f", (float) totalBytesSent / totalBytesExpectedToSend);
      float progress = (float)( totalBytesSent / totalBytesExpectedToSend);
      [SVProgressHUD showProgress:progress status:@"Uploading video..." maskType:SVProgressHUDMaskTypeBlack];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (error)
    {
        NSLog(@"S3 UploadTask: %@ completed with error: %@", task, [error localizedDescription]);
        [SVProgressHUD showErrorWithStatus:@"Error in Uploding."];
    }
    else
    {
         NSLog(@"S3 UploadTask: %@ completed @", task);
        [self PrepareVideoPfFile:VideoId];
              AWSS3GetPreSignedURLRequest does not contain ACL property, so it has to be set after file was uploaded
        AWSS3PutObjectAclRequest *aclRequest = [AWSS3PutObjectAclRequest new];
        aclRequest.bucket = @"your_bucket";
        aclRequest.key = @"yout_key";
        aclRequest.ACL = <key>;
        [[self.awss3 putObjectAcl:aclRequest] continueWithBlock:^id(BFTask *bftask) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (bftask.error)
                {
                    NSLog(@"Error putObjectAcl: %@", [bftask.error localizedDescription]);
                }
                else
                {
                    NSLog(@"ACL for an uploaded file was changed successfully!");
                }
            });
            return nil;
        }];
    }
}

AWS iOS SDK将为您完成最困难的部分。参考http://docs.aws.amazon.com/mobile/sdkforios/developerguide/

使用URL会话将视频上传到AWS服务器

- (void)initBackgroundURLSessionAndAWS:(NSString*)MediaId
{
    VideoId= MediaId;
   AWSStaticCredentialsProvider *credentialsProvider = [AWSStaticCredentialsProvider credentialsWithAccessKey:<Your Access Key> secretKey:<Your Secret Key>];
    AWSServiceConfiguration *configuration = [AWSServiceConfiguration configurationWithRegion:AWSRegionUSEast1 credentialsProvider:credentialsProvider];
    NSURLSessionConfiguration *URLconfiguration;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] == NSOrderedAscending) {
        // iOS7 or earlier
        URLconfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:MediaId];
    } else {
        // iOS8 or later
        URLconfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:MediaId];
    }
    self.urlSession = [NSURLSession sessionWithConfiguration:URLconfiguration delegate:self delegateQueue:nil];
    [AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;
    self.awss3 = [[AWSS3 alloc] initWithConfiguration:configuration];
    NSURL *movieURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] valueForKey:@"mediaURL"]];

    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"Video.MOV"];
    NSData *imageData = [NSData dataWithContentsOfURL:movieURL];
    [imageData writeToFile:path atomically:YES];
    NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
    AWSS3GetPreSignedURLRequest *getPreSignedURLRequest = [AWSS3GetPreSignedURLRequest new];
    getPreSignedURLRequest.bucket = <Your Bucket Id>;
    getPreSignedURLRequest.key = [NSString stringWithFormat:@"%@.MOV",MediaId];
    getPreSignedURLRequest.HTTPMethod = AWSHTTPMethodPUT;
    getPreSignedURLRequest.expires = [NSDate dateWithTimeIntervalSinceNow:3600];
    //Important: must set contentType for PUT request
    getPreSignedURLRequest.contentType = @"movie/mov";;
    [[[AWSS3PreSignedURLBuilder defaultS3PreSignedURLBuilder] getPreSignedURL:getPreSignedURLRequest] continueWithBlock:^id(BFTask *task) {
        if (task.error)
        {
            NSLog(@"Error BFTask: %@", task.error);
            [self showError];
        }
        else
        {
           // [SVProgressHUD dismiss];
            NSURL *presignedURL = task.result;
            NSLog(@"upload presignedURL is: n%@", presignedURL);
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:presignedURL];
            request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
            [request setHTTPMethod:@"PUT"];
            [request setValue:@"movie/mov" forHTTPHeaderField:@"Content-Type"];
            //          Background NSURLSessions do not support the block interfaces, delegate only.
            NSURLSessionUploadTask *uploadTask = [self.urlSession uploadTaskWithRequest:request fromFile:url];
            [uploadTask resume];
        }
        return nil;
    }];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
    // Upload progress
    NSLog(@"Progress : %f", (float) totalBytesSent / totalBytesExpectedToSend);
    float progress = (float)( totalBytesSent / totalBytesExpectedToSend);
    [SVProgressHUD showProgress:progress status:@"Uploading video..." maskType:SVProgressHUDMaskTypeBlack];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (error)
    {
        NSLog(@"S3 UploadTask: %@ completed with error: %@", task, [error localizedDescription]);
        [SVProgressHUD showErrorWithStatus:@"Error in Uploding."];
    }
    else
    {
         NSLog(@"S3 UploadTask: %@ completed @", task);
        [self PrepareVideoPfFile:VideoId];
      AWSS3GetPreSignedURLRequest does not contain ACL property, so it has to be set after file was uploaded
        AWSS3PutObjectAclRequest *aclRequest = [AWSS3PutObjectAclRequest new];
        aclRequest.bucket = @"your_bucket";
        aclRequest.key = @"yout_key";
        aclRequest.ACL = AWSS3ObjectCannedACLPublicRead;
        [[self.awss3 putObjectAcl:aclRequest] continueWithBlock:^id(BFTask *bftask) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (bftask.error)
                {
                    NSLog(@"Error putObjectAcl: %@", [bftask.error localizedDescription]);
                }
                else
                {
                    NSLog(@"ACL for an uploaded file was changed successfully!");
                }
            });
            return nil;
        }];
    }
}

相关内容

最新更新