2015-03-03 102 views
2

代碼調用在postrequest錯誤:無法在迅速

var request = NSMutableURLRequest(URL: NSURL(string:"http://../projects/quotes/index.php/synchronization/get_daily_quotes")!) 
     var session = NSURLSession.sharedSession() 
     request.HTTPMethod = "POST" 
     var err: NSError? 

     var params = ["user_id":"1","number_of_quotes":"2","category_ids":"1"]as NSDictionary 

     request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) // This Line fills the web service with required parameters. 
     request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
     request.addValue("application/json", forHTTPHeaderField: "Accept") 

     var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
      var strData = NSString(data: data, encoding: NSUTF8StringEncoding) 
      var err1: NSError? 
      var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(strData, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary 

      println("json2 :\(jsonResult)") 

      if((err != nil)) { 
       println(err!.localizedDescription) 
      } 
      else { 
       var success = jsonResult["success"] as? Int 
       println("Succes: \(success)") 
      } 
     }) 

     task.resume() 
    } 

我試圖用JSON arguments.it發送postrequest給我的錯誤是「不能援引‘JSONObjectWithData’類型的參數列表「(的NSString? ,選項:NSJSONReadingOptions,錯誤:無)「。爲什麼我得到這個錯誤?任何幫助將不勝感激。

回答

2
var strData = NSString(data: data, encoding: NSUTF8StringEncoding) 

創建一個字符串,而不是NSData的,所以你只需要調用JSONObjectWithData這樣的:

NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary 
+0

它解決了我的問題 – user3823935 2015-03-03 10:55:32

+0

@在這種情況下user3823935不要忘了接受的答案。 – 2015-03-03 10:56:57