• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ios - POST with/JSON Body - Swift 3 - 片段?

[复制链接]
菜鸟教程小白 发表于 2022-12-13 14:17:48 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我只是想通过 Swift3 httprequest 发送一个 JSON 字符串。

尝试使用字典和转义字符串 ...

func getToken(successHandler: @escaping (Any) -> Void, errorHandler: @escaping (Any) -> Void) {

    var request = URLRequest(url: URL(string: "http://my-api.domain.com/getToken")!)

    request.httpMethod = "OST"

    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    do
    {
        // try with Dictionary
        let bodyJson: [String: String] = [
            "username": "theusername"
        ]
        let bodyJsonData = try JSONSerialization.data(withJSONObject: bodyJson, options: [])

        // try with escaped String
        let jsonString = "{" +
            "\"username\": \"theusername\"," +
        "}"
        let jsonStringData = jsonString.data(using: String.Encoding.utf8)


        //request.httpBody = bodyJsonData
        request.httpBody = jsonStringData


        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard error == nil else {
                print(error)
                errorHandler(error)
                return
            }
            guard let data = data else {
                print("Data is empty")
                errorHandler("Data is empty")
                return
            }

            var json: Any? = nil
            do
            {
                json = try JSONSerialization.jsonObject(with: data, options: [])

                DispatchQueue.main.asyncAfter(deadline: .now()) {
                    successHandler(json)
                }
            }
            catch let error as NSError {
                errorHandler(error)
            }
        }

        task.resume()
    }
    catch
    {
        errorHandler(error)
    }
}

我不断得到:

Handle Error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

我找不到如何尝试允许片段,所有示例/教程都是针对 Swift2.x 的:/

不知道该怎么办!



Best Answer-推荐答案


// prepare json data
  let mapDict = [ "1":"First", "2":"Second"]

  let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]

  do {
     let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)

     // create post request
     let endpoint: String = "https://yourAPI"
     let session = URLSession.shared
     let url = NSURL(string: endpoint)!
     let request = NSMutableURLRequest(url: url as URL)
     request.httpMethod = "OST"

     // insert json data to the request
     request.httpBody = jsonData


     let task = session.dataTask(with: request as URLRequest){ data,response,error in
        if error != nil{
           print(error?.localizedDescription)
           return
        }
     }
     task.resume()
  } catch {
     print("bad things happened")
  }

关于ios - POST with/JSON Body - Swift 3 - 片段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39949687/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap