2017-06-01 49 views
0

因此,這裏是我試圖使用Almofire將標題和正文(作爲字符串)發佈到API。Alamofire在iOS中添加字體作爲字符串APP

_ = Alamofire.request("http://myurl", method: .post, parameters: param, encoding: JSONEncoding.default, headers: ["Authorization" : token]) 

     .responseJSON { response in 


      switch response.result { 
      case .success(let data): 
       let json = JSON(data) 

       print(json) 



      case .failure(let error): 
       _ = SweetAlert().showAlert("Data Error!", subTitle: "Something Is Wrong!! Please contact Support", style: AlertStyle.warning) 
      }} 

這工作得很好..

但我無法弄清楚如何通過身體的字符串(這是我通過獲取數據的ID)API不接受任何parametrs(如鍵值或JSON ),除非它只是一個字符串(ID)。任何幫助將不勝感激。

+0

我認爲你正在尋找[這](https://stackoverflow.com/questions/27855319 /請求後與-A-簡單串式體與 - alamofire)。 – Edu

+0

嗨@Edu,我仍然無法找到答案與身體作爲字符串對象insted一個JSON的鍵值.. – Tendy

+0

嗨@ Edu,非常感謝,我找到了你的幫助的答案。 – Tendy

回答

2

添加自定義參數如下圖所示

var customParameters = [String : String]() 
customParameters["key1"] = "Value1" 
customParameters["key2"] = "Value2" 

_ = Alamofire.request("http://myurl", method: .post, parameters: customParameters, encoding: JSONEncoding.default, headers: ["Authorization" : token]) 

    .responseJSON { response in 


     switch response.result { 
     case .success(let data): 
      let json = JSON(data) 

      print(json) 



     case .failure(let error): 
      _ = SweetAlert().showAlert("Data Error!", subTitle: "Something Is Wrong!! Please contact Support", style: AlertStyle.warning) 
     }} 
0

我找到了答案,從https://stackoverflow.com/a/42513496/8099966。這個方法可以在body上sed一個String值。所以,改變了我的代碼,這樣的..

struct JSONStringArrayEncoding: ParameterEncoding { 
    private let myString: String 

    init(string: String) { 
     self.myString = string 
    } 

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { 
     var urlRequest = urlRequest.urlRequest 

     let data = myString.data(using: .utf8)! 

     if urlRequest?.value(forHTTPHeaderField: "Content-Type") == nil { 
      urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type") 
     } 

     urlRequest?.httpBody = data 

     return urlRequest! 
    }} 

然後調用這樣的API ...

_ = Alamofire.request("http://myurl.com", method: .post, parameters: param, encoding: JSONStringArrayEncoding.init(string: "my String id to send"), headers: ["Authorization" : token])