Login with Amazon using Swift 3

The example code on Amazon’s developer website uses Objective-C, so I have decided to write my own version using the latest Swift 3.

Step 0: Follow the instructions from Amazon to create a Login with Amazon (LWA) account and Security Profile. The most important part is the API key for iOS. Modify “info.plist” to add a key “APIKey” with the API key value, and add “URL types” with identifier equals to the app Bundle Identifier while “URL Schemes” equals to “amzn-[BUNDLE_ID]” .

Step 1: Download LoginWithAmazon.framework from here. Make sure all the frameworks are included, including SafariServices and Security.

Step 2: In “AppDelegate.swift”, add import: “import LoginWithAmazon”, then add the following function (this is the step I forgot to add at the beginning, which caused the app fail to redirect back after logged in, and it took me a long time to figure out because there was no error message whatsoever):

func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return AIMobileLib.handleOpen(url, sourceApplication: UIApplicationOpenURLOptionsKey.sourceApplication.rawValue)
    }

Step 3: Create a file named “Settings.swift”:

import Foundation
struct Settings {
    struct Credentials {
        static let APPLICATION_TYPE_ID = "<your_application_type_id>"
        static let CLIENT_ID = "<your_client_id>"
        static let DSN = "123"
        static let SCOPES = ["profile"]
    }
}

Step 4: Create a file named “LoginWithAmazonProxy.swift”:

import Foundation
import LoginWithAmazon

class LoginWithAmazonProxy {

    static let sharedInstance = LoginWithAmazonProxy()

    func login(delegate: AIAuthenticationDelegate) {
        AIMobileLib.authorizeUser(forScopes: Settings.Credentials.SCOPES, delegate: delegate, options: [])
    }
}

Step 5: Modify “ViewController.swift” to implement AIAuthenticationDelegate:

import UIKit
import LoginWithAmazon

class ViewController: UIViewController, AIAuthenticationDelegate {

    @IBOutlet weak var loginWithAmazonBtn: UIButton!

    @IBAction func onClickLoginWithAmazonBtn(_ sender: Any) {
        LoginWithAmazonProxy.sharedInstance.login(delegate: self)
    }

    func requestDidSucceed(_ apiResult: APIResult) {
        if (apiResult.api == API.authorizeUser) {
            AIMobileLib.getAccessToken(forScopes: Settings.Credentials.SCOPES, withOverrideParams: nil, delegate: self)
        }
        else {
            print("Success! Token: \(apiResult.result)")
        }
    }

    func requestDidFail(_ errorResponse: APIError) {
        print("Error: \(errorResponse.error.message)")
    }
}

That’s it! Run the app, click the button, and it will bring the LWA page. Happy coding!

GitHub link: here.

Advertisements