2016-11-20 67 views
1
{"title":"exampleTitle","hashTags":[{"name":"tag1"},{"name":"tag2"}],"uploadFiles": 
[{"fileBytes":"seriesOfBytes\n","filename":"upload.txt"}]} 

這是我想要的身體我想發送到後端。Alamofire 4,Swift 3和建立一個json主體

我使用Swift 3.0和Alamofire 4,我有很多問題。如何正確創建一個包含值和數組值的數組?

我的做法是:

let para:NSMutableDictionary = NSMutableDictionary() 
para.setValue("exampleTitle", forKey: "title") 
let jsonData = try! JSONSerialization.data(withJSONObject: para, options: .init(rawValue: 0)) 
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue) as! String 
print(jsonString) 

這給了我

{"title":"exampleTitle"} 

第二,我alamofire請求.post的樣子以下,並且不工作:

Alamofire.request(postURL, method: .post, parameters: jsonString, encoding: JSONEncoding.default) 
     .responseJSON { response in 
      debugPrint(response) 
    } 

我收到錯誤消息:調用中的額外參數「方法」。如果我不是jsonString使用類型

var jsonString: [String : Any] 

的字符串,它的工作,但我不知道如何把身體到這種類型。

摘要 尋求幫助(例如將是最好的)如何創建身體,以及如何通過Alamofire 4向它發送快捷3到我的後端。

+0

的可能的複製(http://stackoverflow.com/questions/31982513/how-to-send-a-post-request-with-body- [如何在迅速BODY發送POST請求]在我迅速) –

回答

10

您需要將參數作爲[String:Any]字典傳遞,因此請創建一個字典作爲傳遞JSON。

let params = [ 
       "title":"exampleTitle", 
       "hashTags": [["name":"tag1"],["name":"tag2"]], 
       "uploadFiles":[["fileBytes":"seriesOfBytes\n","filename":"upload.txt"]] 
      ] 

現在通過這個params作爲Alamofire請求中的參數。

Alamofire.request(postURL, method: .post, parameters: params, encoding: JSONEncoding.default) 
    .responseJSON { response in 
     debugPrint(response) 
} 
+0

之前,我把它標記爲接受一個更多的問題:我也有標題,我把它們放在請求中,他們如何需要格式化?我試圖將它們添加爲參數,但它再次給了我額外的通話消息。 –

+0

對於標題檢查這一個https://github.com/Alamofire/Alamofire#http-headers,如果你仍然沒有得到問這裏的新問題。 –

+0

檢查傳遞標頭http://stackoverflow.com/a/39512635/6433023 –