I've been writing swift/php/sql for 3 months now... (I know I'm a rookie). I can create simple POST strings and issue http requests... etc.
Now I'm trying to push multiple objects to my server to add to my database. So I'm thinking the best way to transport the objects is to use a big json string. Maybe not... idk. I have been unsuccessful at creating the multiple object json string to post. Ideally, I'd like a string that PHP json_decode($myJsonString) will decode directly... I've created a playground to use as a test case. The call to JSON(myPlaceArray) results in "unknown".
Suggestions on how fix this or and easier way welcome! thank you!
import UIKit
import SwiftyJSON
class myClass {
public struct Place {
var PlaceId = String()
var name = String()
var address = String()
var latitude = Double()
var longitude = Double()
}
}
var myPlaceArray = [myClass.Place()]
var myPlace = myClass.Place()
for i in 0..<3 {
myPlace.PlaceId = "\(i)"
myPlace.address = "My Address \(i)"
myPlace.name = "My Name \(i)"
myPlace.latitude = 37.123
myPlace.longitude = -127.321
if(i==0){
myPlaceArray[0] = myPlace
}
else {
myPlaceArray.append(myPlace)
}
}
print(myPlaceArray[0])
let json = JSON(myPlaceArray)
print(json) // results: "unknown"
let jsonMyPlaceArray = JSON(myPlaceArray)
print(jsonMyPlaceArray)
//setup json post data
//send HTTP POST
let myUrl = NSURL(string: "https://myUrl.php")
let request = NSMutableURLRequest(url: myUrl! as URL)
request.httpMethod = "POST"
let postString = "jsonPlaces=\(String(describing: jsonMyPlaceArray))"
print(postString) // jsonPlaces=unknown
//.... make request
I found very useful the JSONUtils: https://github.com/peheje/JsonSerializerSwift You can model your message as Swift classes and later serialize them using this library. This is a piece of the code where I post a JSON message containing text data and an encoded image:
class TeamsSao : BaseSao {
class func update ( request : TeamUpdateRequest, callback : @escaping (TeamUpdateResponse!) -> Void ) {
var strUrl : String = getServiceUrl() + "/index.php"
strUrl += "?avoid_cache=" + StringUtils.randomString (length: 24)
let url: URL = URL(string: strUrl)!
var urlRequest: URLRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.timeoutInterval = 120000
urlRequest.cachePolicy = .reloadIgnoringLocalCacheData
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
let bodyStr:String = "msg=" + JSONUtils.toJson(request)//"pseudo=test"
urlRequest.httpBody = bodyStr.data(using: String.Encoding.utf8)
let session = URLSession.shared
session.dataTask(with: urlRequest, completionHandler:
{ (data, response, error) in
//print(data)
//print(response)
//print(error)
var result : TeamUpdateResponse!
if (error == nil) {
if let httpResponse = response as? HTTPURLResponse {
if (httpResponse.statusCode < 200) || (httpResponse.statusCode >= 300) {
result = TeamUpdateResponse()
result.status = TeamUpdateResponse.RESULT_EXCEPTION
result.errorDescription = "Response Status: \(httpResponse.statusCode)"
} else {
result = TeamUpdateParser.parse(data: data!)
}
}
} else {
//print("A connection error occurred, here are the details:
\(error)")
result = TeamUpdateResponse()
result.status = TeamUpdateResponse.RESULT_EXCEPTION
result.errorDescription = error as! String!
}
callback (result)
}
).resume()
}
}
A few points to understand: