首页 > 解决方案 > 在 swift 中使用字典和 utf-8 进行发布请求

问题描述

我需要发出一个发布请求,以在需要用 utf-8 编码的发布请求正文中发送一个字典,我在下面尝试了这个,但它给出了一个错误:

  let DicObject: NSMutableDictionary = NSMutableDictionary()
        DicObject.setValue("cf", forKey: "a")
        DicObject.setValue("", forKey: "scs")
        DicObject.setValue("Uploads/" + nameOfFile, forKey:"p")

当我尝试做

 request.httpMethod = "POST"
      //  request.httpBody = jsonObject as Data
        request.addValue("Content-Type", forHTTPHeaderField: "application/x-www-form-urlencoded; charset=utf-8")

它不起作用,有谁知道如何将jsonObject编码转换为 utf-8

谢谢。

标签: jsonswiftutf-8

解决方案


你可以使用这个 Alamofire 方法

      mydict = [:] // Your parameters here

      if let theJSONData = try? JSONSerialization.data(
            withJSONObject: mydict,
            options: []) {
            let theJSONText = String(data: theJSONData,
                                     encoding: .ascii)
            multipartFormData.append((theJSONText?.data(using: .utf8)!)!, withName: "bulkData")
        }

推荐阅读