Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post dictionary from Swift to PHP

How can a dictionary generated in Swift be posted as parameter in a PHP URL?

Specifically, the task is to update many fields on a hosted database. Rather than define new values for each field as a separate parameter, I am looking to pass a dictionary where the keys are the field names and the values are the new values. This data already exists as a Dictionary<String, String> in Swift - how can it be tacked on to the php url in the following format:

"http://server/directory/targetScript.php/?recordId=\(recId)&newFieldArray=\(itemDict)"

Where:

recId = the record id that is being updated (as an example of passing a separate variable along with the dictionary)

itemDict= the dictionary generated in Swift

Here is the current code: ... which returns an error showing url as "nil"

class func updateItemInfo ( recordId:String, updatedDict:Dictionary<String, String> ) -> Void {
    //recordId = the FileMaker recordId of the item being updated
    //updatedDict = the primaryKey of the current item

    //direct to php file location
    let server:String = "myServer.com"
    let phpFile:String = "/php/UpdateRecord.php"

    let baseURL = NSURL(string: "http://\(server)\(phpFile)")
    let url = NSURL(string: "?recordId=\(recordId)&newData=\(updatedDict)", relativeToURL: baseURL)
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
    var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 20.0)
    request.HTTPMethod = "POST"

    // set data
    var dataString = ""
    let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    request.HTTPBody = requestBodyData

    var response: NSURLResponse? = nil
    var error: NSError? = nil
    let reply: NSData! = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
    let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
    println(results)
}
like image 641
Michael Voccola Avatar asked Dec 14 '25 13:12

Michael Voccola


1 Answers

Why don't you use JSON to pass the values.

  1. Convert the Dictionary to JSON String.
  2. If you are sending this data as a query string; you will have to URL encode it
  3. Finally you can send it to PHP; where it will reach as a single parameter in $_GET. There you will need PHP's json_decode to get an associated array back from it.
like image 170
Malay Sarkar Avatar answered Dec 17 '25 05:12

Malay Sarkar