3

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)
}
Michael Voccola
  • 1,827
  • 6
  • 20
  • 46
  • 2
    Use the `NSJSONSerialization` class to convert the dictionary to an `NSData` object, and set that as the `HTTPBody`. Then in PHP do `json_decode(file_get_contents('php://input'))` to read the data. – Abhi Beckert Feb 01 '15 at 04:15

1 Answers1

2

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.
Community
  • 1
  • 1
Malay Sarkar
  • 411
  • 3
  • 9