2017-10-17 2 views
0

ユーザーからデータを収集してWebサービスに送信しようとしていますが、「JSON書き込みでトップレベルの型が無効です」というエラーが表示されます。関数を呼び出すと、すべてのデータがuserhealthprofile変数に正しく渡されます。しかし、何かが私のJSONコードに問題があるSwiftにユーザー入力JSONを投稿する

完全なエラーメッセージが、これは、これはUSERPROFILEのように見えるものである

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() 
} 

私はのためのjsonobjectとして送信するために必要なものです私のウェブサービス。

class UserHealthProfile { 

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

} 
+0

のように(送信者ANYOBJECTが)あなたが取得しているエラーを追加... – Ladislav

+0

完全エラーを追加しました –

+0

userHealthProfileは '[[String:Any]]'または '[String:Any]'ではありません – Marcel

答えて

0

私はあなたがウェブAPIを呼び出すためAlamofireを使うべきだと思う... ここでは、サンプルコードでは、要件に応じています。私は、これはあなたを助けることを願っています

...あなたの@IBActionのFUNCのsubmitActionに呼び出し

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 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) 

} 
+0

これは本当に素晴らしいと私は必要なコードを本当に単純化されます。もともとは素早いプログラマではありませんでしたが、ヘルスキットのコードはC#xamarinでは動作しないため、迅速に切り替える必要がありました。ありがとう、これを試してみましょう。 –

+0

Alamofire.request(.POST、 "http://www.thisismylink.com/postName.php"、parameters:parametersToSend??[String:AnyObject]、encoding:.URL)コードのこの部分でエラーが発生しました。 .responseJSON 「http://www.thisismylink.com/postName.php」は呼び出し時の余分な引数です。 –

+0

スイフト3またはスウィフト4を使用していますか? – Zee

関連する問題