如何在v2.1上将视频作为Multipart视频上传iOS上传到亚马逊s3

时间:2015-04-01 06:52:22

标签: ios

如何将视频上传到亚马逊s3作为分段上传方法。如果有人知道甚至有一些想法如何解决这个问题,请给我一些建议。

非常感谢你的时间!

3 个答案:

答案 0 :(得分:4)

首先使用URLSession创建AWS Object&用委托方法处理它

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

使用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;
        }];
    }
}