2015-08-13 67 views
0

自定義參數POST請求我買了Alamofire post請求一個問題,如果我有什麼參數,如:與SWIFT

let parameters = [ 
    "foo": "bar", 
    "baz": ["a", 1], 
    "qux": [ 
     [["x": 1],["y": 2]], 
     [["x": 1],["y": 2]], 
     [["x": 1],["y": 2]] 
    ] 
] 

Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters) 

發佈請求將無法正常工作!你有任何想法如何解決?

+1

意思「巴茲」:[「A」:1]? – Azzaknight

回答

0

這種變種工作

let parameters = [ 
      "foo": "bar", 
      "baz": ["a", 1], 
      "qux": [ 
       [["x": 1],["y": 2]], 
       [["x": 1],["y": 2]], 
       [["x": 1],["y": 2]] 
      ] 
     ] 
     let data = NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.PrettyPrinted,error:nil) 

     let post = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String 

     httpPost("http://httpbin.org/post", postData: post){res, code in 
      println(res) 
     } 

//將函數代碼上,你可以發佈您的數據

func httpPost(url:String, postData: String, completion: (String, Int) -> Void) { 

      var request = NSMutableURLRequest(URL: NSURL(string: url)!) 

      request.HTTPMethod = "POST" 

     request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding); 

     request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 
     request.addValue("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36", forHTTPHeaderField: "User-Agent") 
     request.addValue("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", forHTTPHeaderField: "Accept") 
     request.addValue("gzip, deflate, sdch", forHTTPHeaderField: "Accept-Encoding") 
     request.addValue("max-age=0", forHTTPHeaderField: "Cache-Control") 

     var session = NSURLSession.sharedSession() 

     let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in 
      if let HTTPResponse = response as? NSHTTPURLResponse { 
       let statusCode = HTTPResponse.statusCode 

      completion(NSString(data: data, encoding: NSUTF8StringEncoding) as! String, statusCode) 
      } 
     }) 

     task.resume() 

    } 
1

不能發送結構在HTTP請求體編碼形式的行動。也許你想把它作爲json發送。在這種情況下可以調用這樣請求方法:

Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)