Integrate AWS S3 Presigned URL iOS Swift 3

Posted By : Vasu Saini | 20-Sep-2017

Today we will learn about how to use Amazon web services in ios to get presigned URL to access the private files of the Amazon server.

Step 1.  Create a new project with single page view application.

Step 2.  Install pod in the project as following
              pod 'AWSS3'

Step 3. After successful installation, we have to do few changes in Info.plist

	<key>ITSAppUsesNonExemptEncryption</key>
	<false/>
	<key>LSRequiresIPhoneOS</key>
	<true/>
	<key>NSAppTransportSecurity</key>
	<dict>
		<key>NSAllowsArbitraryLoads</key>
		<true/>
		<key>NSExceptionDomains</key>
		<dict>
			<key>amazonaws.com</key>
			<dict>
				<key>NSIncludesSubdomains</key>
				<true/>
				<key>NSThirdPartyExceptionMinimumTLSVersion</key>
				<string>TLSv1.0</string>
				<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
				<false/>
			</dict>
			<key>amazonaws.com.cn</key>
			<dict>
				<key>NSIncludesSubdomains</key>
				<true/>
				<key>NSThirdPartyExceptionMinimumTLSVersion</key>
				<string>TLSv1.0</string>
				<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
				<false/>
			</dict>
		</dict>
	</dict>

Step 4. Paste the above code in your info.plist in <plist> tag.

Step 5. The above mention code is for App transport seacurity , we have to allow our app to communicate via URLs from the third party as mentioned in the code we have allowed www.amazon.com for data transactions.

Step 6. Now there are two ways to setup AWS in your application as follows
             1.Amazon Cognito Mode
             2.Open Mode

Step 7. You can use any one of them, In case of Cognito mode you have required your identityPoolId and AWS server region to access your Cognito id to generate a coginto mode URL to access private files.

Step 8. To setup AWS we have to do something in AppDelegate.swift

Step 9. In case of Open Mode, you have required three keys to generate a presigned URL to access private files of amazon server one is access key and another one is secret key and AWS server region.

    //MARK:- AWS SetUp
    func setUpAWS(){
        //Using Open mode
        
        let credentialsProvider = AWSStaticCredentialsProvider(accessKey: "demo_access_key", secretKey: "demo_secret_key")
        let configuration = AWSServiceConfiguration.init(region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)
        AWSServiceManager.default().defaultServiceConfiguration = configuration
        
        //Using Identity Pool Id for cognito mode
        
//        let credentialProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "YourIdentityPoolId")
//        let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialProvider)
//        AWSServiceManager.default().defaultServiceConfiguration = configuration
//        let cognitoId = credentialsProvider.identityId
    }

Step 10. As shown in code snippet above setup of AWS in ios using swift3 both ways.

Step 11. Import AWSS3 and  Copy the above method and paste it in your AppDelegate.swift and call setUpAWS() in didFinishLaunchingWithOptions

Step 12. If you are using open menthod then delete commented code and replace your server region, secret key and access key.

Step 13. Otherwise, uncomment the commented code and replace your server region and your poolId and also delete pre-uncommented code or code for the open method.

Step 14. Now your AWS setup is completed in your project now all you have to do is for generating a Presigned URL

Step 15. Create a new swift file in your project and copy paste the following code in the file.

import UIKit
import Foundation
import AWSS3

let S3BucketName = "demo_bucketName"
class AWSService {
    var preSignedURLString = ""

    func getPreSignedURL( S3DownloadKeyName: String)->String{
        let getPreSignedURLRequest = AWSS3GetPreSignedURLRequest()
        getPreSignedURLRequest.httpMethod = AWSHTTPMethod.GET
        getPreSignedURLRequest.key = S3DownloadKeyName
        getPreSignedURLRequest.bucket = S3BucketName
        getPreSignedURLRequest.expires = Date(timeIntervalSinceNow: 3600)
        
        AWSS3PreSignedURLBuilder.default().getPreSignedURL(getPreSignedURLRequest).continueWith { (task:AWSTask<NSURL>) -> Any? in
            if let error = task.error as NSError? {
                print("Error: \(error)")
                return nil
            }
            self.preSignedURLString = (task.result?.absoluteString)!
            return nil
        }
        return self.preSignedURLString
    }
    
}

Step 16. The function written in the class returns a presigned URL corresponding to bucket name defined above the class and downloadKey passed in the function.

Step 17. Replace the bucket name as with yours if it is dynamic then make it is as functions parameter.

Step 18 The below line will get you your required signed URL of your private file kept on Amazon server.

 let signedUrl = URL(string:AWSService().getPreSignedURL(S3DownloadKeyName: "demo_key")

 

About Author

Author Image
Vasu Saini

Vasu Saini is Passionate to deploy ideas into real world, Have zeal to learn new technologies. working as iOS Developer in Oodles Technologies. Sports Freak, Calisthenics ,Parkour, Love to play football, swimmer, athletics etc

Request for Proposal

Name is required

Comment is required

Sending message..