Swift对象数组到JSON - > POST - > PHP json_decode()到PHP对象数组

时间:2017-04-03 17:25:04

标签: php arrays json swift post

我已经写了swift / php / sql 3个月了......(我知道我是菜鸟)。我可以创建简单的POST字符串并发出http请求......等 现在我正在尝试将多个对象推送到我的服务器以添加到我的数据库中。所以我认为传输对象的最佳方法是使用一个大的json字符串。也许不... ... idk。我没有成功创建要发布的多个对象json字符串。理想情况下,我想要一个PHP json_decode($ myJsonString)将直接解码的字符串...我已经创建了一个用作测试用例的游乐场。对JSON(myPlaceArray)的调用导致“未知” 关于如何解决这个或更简单方式的建议!谢谢!

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

playground_image

1 个答案:

答案 0 :(得分:0)

我发现JSONUtils非常有用: https://github.com/peheje/JsonSerializerSwift 您可以将消息建模为Swift类,然后使用此库对它们进行序列化。 这是我发布包含文本数据和编码图像的JSON消息的代码片段:

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:\n \(error)")
                result  = TeamUpdateResponse()
                result.status = TeamUpdateResponse.RESULT_EXCEPTION
                result.errorDescription = error as! String!
            }
            callback (result)
    }
        ).resume()

}

}

要理解几点:

  1. TeamUpdateRequest是包含要发送的数据的类
  2. TeamUpdateResponse是包含响应的类
  3. 使用Swift 3,您应该使用回调函数。此方法接收回调函数,因此,当帖子完成后,将解析响应,然后调用回调函数。