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