Swift + Alamofire: User Login & MySQL

Hi All,

I’ve been working on a project using Swift and DreamFactory. I searched around online and couldn’t find many concrete examples of accessing the DreamFactory API from Swift using Alamofire.

I’ve added my code below, just in case it’s any use to anyone. Its not the neatest or the most efficient, but it works and it does the following:

  • User Login to get a session token.

  • Adding/reading records from a MySQL database through DreamFactory.

Alamofire & SwiftJSON libraries are used in these code examples:

import Alamofire
import SwiftyJSON

User Authentication:

/**
 Function that logs the user in and stores the session token for later use
 **/
func logIn() {
    
    let parameters = [
        "email": username, //email
        "password": password //password
    ]
    var statusCode: Int = 0
    Alamofire.request(.POST, "http://{dreamfactoryinstance}/api/v2/user/session", parameters: parameters, encoding: .JSON)
        .responseJSON { response in
            statusCode = (response.response?.statusCode)! //Gets HTTP status code, useful for debugging
            if let value: AnyObject = response.result.value {
                //Handle the results as JSON
                let post = JSON(value)
                if let key = post["session_id"].string {
                    //At this point the user should have authenticated, store the session id and use it as you wish
                } else {
                    print("error detected")
                }
            }
    }
}

Creating MySQL records:

/**
 Function to create a record in the MySQL database
 **/
func createMySQLRecord() {
    let headers = [
        "X-DreamFactory-API-Key": {yourApplicationApiKey}, //your application api key for DreamFactory
        "X-DreamFactory-Session-Token:": {sessionToken} //the session token generated in the function above
    ]
    let parameters = [
        "forename": "Ainsley",
        "surname": "Harriott",
        "email": "test@test.fr",
        "country": "United Kingdom"
    ]
    var statusCode: Int = 0
    Alamofire.request(.POST, "http://{dreamfactoryinstance}/api/v2/mysql/_table/{table name}", headers: headers, parameters: parameters, encoding: .JSON)
        .responseJSON { response in
            statusCode = (response.response?.statusCode)! //useful for debugging again
            if let value: AnyObject = response.result.value {
                //the record should have been created, any response from the server will be created as JSON and accessable here
                let post = JSON(value)
                //print(post)
            }
    }
}

Reading MySQL records:

/**
 Function to retrieve a record from the MySQL database
 **/
func retrieveMySQLRecord(){
    var parameters = [
        "api_key": {yourApplicationApiKey}, //your application api key for DreamFactory
        "session_token": {sessionToken}, //the session token generated in the function abov
        "filter": "columnName=" + "fieldContents"
    ]
    Alamofire.request(.GET, "http://{dreamfactoryinstance}/api/v2/mysql/_table/[table name}", parameters: parameters)
        .responseJSON { response in
            
            if let value: AnyObject = response.result.value {
                
                let post = JSON(value)
                
                if let resData = post["resource"].arrayObject { //Get the data into an array
                    
                    self.arrRes = resData as! [[String:AnyObject]] //Transfer the data to an array other functions can access
                    
                }
                
            }
    }
    
}

Hope it’s useful,

Sam

2 Likes

Hey Sam, thanks for the example!

Hi @samkirsten
Thank you for all of useful information.
I have a question, you mentioned “sessionToken” two times in your code and you said it’s generated in function above. Can you be more specific please? I don’t know how to pass the sessionToken value to func createMySQLRecord() and func retrieveMySQLRecord() it gives me error Use of unresolved identifier ‘sessionToken’

Hi @Farhad33,

Thanks for pointing this out, I should have probably made it a bit clearer.

The two MySQL examples require a user to have logged in and created a session, that is what the log in function does. If you store the value returned as the session token then you can reuse this in the other functions. So in the log in function you would store the token like this:

 if let key = post["session_id"].string {
          sessionToken = key
           //At this point the user should have authenticated, store the session id and use it as you wish
  }

You will have to create the sessionToken variable at the top of the class, I haven’t included that here.

Sam

1 Like

Hii,Actually i have one confusion about the headers what can i put on applicationApiKey ?? how can i get it??

Hello @bhavna.lintel

The applicationAPIKey is used to consume DreamFactory APIs. Each app has a unique API key that is sent with each request. When no session token is provided, the request is considered to be from an unauthenticated user and the system uses the API key to look up the default role for the app. The API can be generated in the DreamFactory dashboard.

More information on creating an app and generating API keys can be found here on DreamFactory guide

Let us know if you any more questions