Swift + Alamofire: User Login & MySQL


#1

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

Hey Sam, thanks for the example!


#3

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’


#4

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


#5

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