Ios_Dev98
Ios_Dev98

Reputation: 81

How to upload video to Amazon s3 as Multipart video upload iOS on v2.1

How to upload video to amazon s3 as multipart upload method. If someone know or even have some ideas how to solve this problem please give me some advise.

Thanks a lot for your time!

Upvotes: 3

Views: 2151

Answers (3)

Hemali Luhar
Hemali Luhar

Reputation: 359

Use URL Session to upload video to AWS server

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

Upvotes: 0

Hemali Luhar
Hemali Luhar

Reputation: 359

First use URLSession to create AWS Object & handle it with delegate methods

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

Upvotes: 4

Xcoder
Xcoder

Reputation: 1807

AWS iOS SDK will do the most difficult part for you. Refer; http://docs.aws.amazon.com/mobile/sdkforios/developerguide/

Upvotes: 0

Related Questions