2017-08-01 85 views
0

我要發佈數據作爲參數是這樣的:Alamofire:發送參數

{ 
    "data": 
    [ 
     { 
      "nik" : "lalaal" 
     } 
    ] 
} 

我怎樣寫在斯威夫特3這些參數使用Alamofire

我想:

let parameter: Parameters = [ 
       "data":[[ 
        "nik" : self.nik, 
        "check_type" : "IN", 
        "tanggal" : "01-08-2017 18:22:00", 
        "long" : String(locationList[projectChoosen].long!), 
        "lat" : String(locationList[projectChoosen].lat!), 
        "id_loc" : locationList[projectChoosen].id_project, 
        "id_project" : nil, 
        "nama_project" : locationList[projectChoosen].nama_project, 
        "barcode" : "", 
        "foto": "", 
        "mime_type" : "image/jpeg" 

        ]] 
      ] 
+1

顯示你試過代碼 –

+0

試試這個:Alamofire.request( 「URL」,方法:.POST,參數:參數,編碼:JSONEncoding.default) – KKRocks

+0

https://stackoverflow.com/a/45437228/ 1242673 –

回答

2

可以使用下面的代碼。

let dicRequest: NSDictionary = ["userid" : "test", "password" : "test123"] 

let postParams:NSDictionary = [ 
    "data": dicRequest 
] 
let requestURL: String = String(format: "%@/Login", serverURL) 
Alamofire.request(requestURL, method: .post, parameters: postParams as? [String : AnyObject], encoding: JSONEncoding.default, headers: [:]) 
    .responseJSON { response in switch response.result { 

    case .success(let JSON): 
     print("response :-----> ",response) 
    case .failure(let error): 
     print("Request failed with error: \(error)") 

     } 
} 
+0

不能:(謝謝你的幫助 –

+0

我已經找到答案[「data」:[dicRequest]] –

+0

好的 謝謝... – shahnilay86

1

您可以在此甲首先創建一個Dictionary對象

{ 
    "data": 
    [ 
     { 
      "nik" : "lalaal" 
     } 
    ] 
} 

那之後,你可以使用這個轉換NSJSONSerlisation以JSON字符串 而不是使用後Almofire。

let array: [[String: String]] = [["nik": "lalaal"]] 
let data = try JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions.prettyPrinted) 
let string = String(data: data, encoding: String.Encoding.utf8) 
let postParam: [String: String] = ["data": string] 

let _ = Alamofire.request(apiType.url!, method: apiType.type!,parameters: postParam, encoding: JSONEncoding.prettyPrinted, headers: nil).validate(statusCode: 200..<500).responseJSON { (response) in 

} 
+0

can not bro :(無論如何感謝您的幫助 –

0

下面是使用Alamofire和張貼字典作爲參數的示例請求:

let dataArray: [[String: String]] = [["nik": "lalaal"]] 
let param: [String: [Any]] = ["data": dataArray]  
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: nil).responseJSON { response in }