在Swift中发布用户输入JSON

时间:2017-10-17 08:55:55

标签: json swift post

我正在尝试从用户收集数据并将其发送到Web服务,但是我收到错误" JSON写入中的顶级类型无效"我正在从另一个函数中的healthstore收集步骤,所有数据都正确地传递到userhealthprofile变量,因为它可以打印出来。但是我的JSON代码出了点问题

完整的错误消息是

2017-10-17 09:30:57.170950+0200 IphoneReader[347:40755] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
*** First throw call stack:
(0x1d0b3b3d 0x1c33b067 0x1d0b3a85 0x1da763c1 0x9aa50 0x9bb60 0x2231a3b5 0x2231a349 0x22304979 0x22321f87 0x2286bf1b 0x22868833 0x22868423 0x22867849 0x223146f5 0x222e62bb 0x22a797f7 0x22a7419b 0x22a7457d 0x1d06ffdd 0x1d06fb05 0x1d06df51 0x1cfc11af 0x1cfc0fd1 0x1e76bb41 0x22349a53 0xa4d18 0x1c7ae4eb)
libc++abi.dylib: terminating with uncaught exception of type NSException

代码

@IBAction func submitAction(sender: AnyObject) {

    userHealthProfile.name = nameLabel.text
    print(userHealthProfile.name)

    userHealthProfile.age = Int(ageLabel.text!)
    print(userHealthProfile.age)

    userHealthProfile.heightInMeters = Int(heightLabel.text!)
    print(userHealthProfile.heightInMeters)

    userHealthProfile.weightInKilograms = Int(weightLabel.text!)
    print(userHealthProfile.weightInKilograms)

    for element in stepy.step {
        print(element)
    }

    userHealthProfile.totalStepsCount = stepy.step

    print("pressing button")

    //create the url with URL
    let url = URL(string: "www.thisismylink.com/postName.php")! 
    //change the url

    //create the session object
    let session = URLSession.shared

    //now create the URLRequest object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "POST" //set http method as POST

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: userHealthProfile, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
    } catch let error {
        print(error.localizedDescription)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }
        guard let data = data else {
            return
        }
        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print(json)
                // handle json...
            }
        } catch let error {
            print(error.localizedDescription)
        }
    })
    task.resume()
}

这就是userprofile的样子,这是我需要作为我的Web服务的jsonobject发送的内容。

class UserHealthProfile {

    var name: String?
    var age: Int?
    var totalStepsCount: Array<Any>!
    var heightInMeters: Int?
    var weightInKilograms: Int?

}

1 个答案:

答案 0 :(得分:0)

我认为您应该使用Alamofire来调用Web API .. 以下是根据您的要求提供的示例代码。

我希望这会对你有帮助......

func Submit(parametersToSend:NSDictionary)
{


Alamofire.request(.POST, "http://www.thisismylink.com/postName.php",parameters: parametersToSend as? [String : AnyObject], encoding: .URL).responseJSON
    {
        response in switch response.2
        {
        case .Success(let JSON):
            print(JSON)
            let response = JSON as! NSDictionary
            print("My Web Api Response: \(response)")
            break
        case .Failure(let error):
            print("Request failed with error: \(error)")
            break
        }

     }

}

函数调用@IBAction函数submitAction(sender:AnyObject),如下所示

@IBAction func submitAction(sender: AnyObject) {

let steps  = stepy.step
let name = nameLabel.text!
let age = Int(ageLabel.text!)
let height = Int(heightLabel.text!)
let weight = Int(weightLabel.text!)
let parameters = [
      "name": name
      "age": age
      "totalStepsCount": steps
      "heightInMeters": height
      "weightInKilograms": weight
       ]
 self.submit(parametersToSend:parameters)

}