【问题标题】:Swift: Alamofire Post斯威夫特:阿拉莫菲尔邮报
【发布时间】:2016-07-18 23:11:47
【问题描述】:

我一直在开发一个应用程序,我必须使用 alamofire 来发布。 但是,我不断收到错误,说

失败 错误:反馈提交失败。 Optional("操作无法完成。JSON无法序列化。输入数据为nil或零长度。")

我的代码是这样的

let reportJSON: [String : AnyObject] = [
    "Name" : nameTextField.text!,
    "Message" : reportTextView.text!
  ]
Alamofire.request(.POST, "API", parameters: reportJSON, encoding: .JSON).responseJSON{ response in
    print(response.result)

    guard response.result.error == nil else{
      print("Error: feedback submission failed.")
      print(response.result.error?.localizedDescription)
      return
    }

    if let responseValue = response.result.value{
      let recipeList = JSON(responseValue)
      print(recipeList)
    }
}

我对 .GET 没有任何问题,但我不知道如何使用 .POST。 任何帮助表示赞赏。

【问题讨论】:

  • 我解决了这个问题。也许对其他人来说很明显,但我收到的数据不是 JSON 格式的。所以我不得不使用 responseData,而不是 responseJSON。

标签: json swift alamofire


【解决方案1】:

看来您没有传递正确的 URL,而不是“API”更改为帖子的有效 URL。

【讨论】:

  • 我使用的是公司的私有 url,所以对于这个,我只是调用 API,但在我的应用程序中,它使用了正确的 url
【解决方案2】:

您可以使用以下方法使用 Alamofire 和 Swift 3 进行 POST 请求:

let headers = [
               "Accept": "application/json",
               "Authorization" : "Authorization: Bearer ", //if any
               "Cookie" : "Cookie" //if any
              ]

let parameterDict: NSDictionary = NSDictionary.init(objects: [nameTextField.text!, reportTextView.text!], forKeys: ["Name" as NSCopying,"Message" as NSCopying])

Alamofire.request("API",method: .post, parameters: parameterDict as? [String : AnyObject] , encoding:JSONEncoding.default, headers:headers) .responseJSON {  response in switch response.result {

     case .success(let JSON):
         print("Success with JSON: \(JSON)")
         let response = JSON as! NSDictionary

     case .failure(let error):
         print("Request failed with error: \(error)")


         }
    }

【讨论】:

    【解决方案3】:

    您可以使用以下代码对 post 方法进行 JSON 解析。

       Alamofire.request("URL" , method : .post,
                          headers: headers)
            .responseJSON { response in
                // do whatever you want here
                switch response.result {
                case .failure(let error): break
                    self.popupp(elrtdata : "Please try again latter.")
                case .success(let responseObject):
    
                    if((response.result.value) != nil) {
    
                        do{
                            let swiftyJsonVar = JSON(response.result.value!)
                            print(swiftyJsonVar) }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      • 2017-07-22
      相关资源
      最近更新 更多