NSURLSession and amazon S3 uploads

后端 未结 7 1842
傲寒
傲寒 2020-12-12 21:27

I have an app which is currently uploading images to amazon S3. I have been trying to switch it from using NSURLConnection to NSURLSession so that the uploads can continue w

7条回答
  •  北海茫月
    2020-12-12 21:48

    For background uploading/downloading you need to use NSURLSession with background configuration. Since AWS SDK 2.0.7 you can use pre signed requests:

    PreSigned URL Builder** - The SDK now includes support for pre-signed Amazon Simple Storage Service (S3) URLs. You can use these URLS to perform background transfers using the NSURLSession class.

    Init background NSURLSession and AWS Services

    - (void)initBackgroundURLSessionAndAWS
    {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:AWSS3BackgroundSessionUploadIdentifier];
        self.urlSession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
        AWSServiceConfiguration *configuration = [AWSServiceConfiguration configurationWithRegion:DefaultServiceRegionType credentialsProvider:credentialsProvider];
        [AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;
        self.awss3 = [[AWSS3 alloc] initWithConfiguration:configuration];
    }
    

    Implement upload file function

    - (void)uploadFile
    {
        AWSS3GetPreSignedURLRequest *getPreSignedURLRequest = [AWSS3GetPreSignedURLRequest new];
        getPreSignedURLRequest.bucket = @"your_bucket";
        getPreSignedURLRequest.key = @"your_key";
        getPreSignedURLRequest.HTTPMethod = AWSHTTPMethodPUT;
        getPreSignedURLRequest.expires = [NSDate dateWithTimeIntervalSinceNow:3600];
        //Important: must set contentType for PUT request
        getPreSignedURLRequest.contentType = @"your_contentType";
    
        [[[AWSS3PreSignedURLBuilder defaultS3PreSignedURLBuilder] getPreSignedURL:getPreSignedURLRequest] continueWithBlock:^id(BFTask *task) {
            if (task.error)
            {
                NSLog(@"Error BFTask: %@", task.error);
            }
            else
            {
                NSURL *presignedURL = task.result;
                NSLog(@"upload presignedURL is: \n%@", presignedURL);
    
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:presignedURL];
                request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
                [request setHTTPMethod:@"PUT"];
                [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
    
    //          Background NSURLSessions do not support the block interfaces, delegate only.
                NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromFile:@"file_path"];
    
                [uploadTask resume];
            }
            return nil;
        }];
    }
    

    NSURLSession Delegate Function:

    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
    {
        if (error)
        {
            NSLog(@"S3 UploadTask: %@ completed with error: %@", task, [error localizedDescription]);
        }
        else
        {
    //      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;
            }];
        }
    }
    

提交回复
热议问题