ios - 快速从http请求中检索json数据

标签 ios swift

我是 swift 的新手,因此是这个问题的新手。我想将我的 http 调用包装到这个签名的函数中。

func httpPost()-> Any

此代码有效,但我如何将此代码包装在我想要的函数签名中。

let headers = [
    "Content-Type": "application/json",
    "cache-control": "no-cache"
]
let parameters = [
    "client_id": "xxx",
    "client_secret": "yyy"
    ] as [String : Any]

let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])

var request = URLRequest(url: URL(string: "http://xxx.xxx")! as URL,
                                  cachePolicy: .useProtocolCachePolicy,
                                  timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData

let session = URLSession.shared
let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in
    guard let data = data else {return}
    do{
        try validate(response)
        let json = try JSONSerialization.jsonObject(with: data, options: [])

    }catch{
        print(error)
    }
    //print(String(describing: data))
}

dataTask.resume()

我想在此处以 Any 形式返回 json 对象

最佳答案

在阻塞线程之前,您不能在异步函数中返回直接值,这是个坏主意,所以您需要完成

func httpPost(completion:@escaping(_ ret:Any?,err:Error?) -> Void)

    let headers = [
        "Content-Type": "application/json",
        "cache-control": "no-cache"
    ]
    let parameters = [
        "client_id": "xxx",
        "client_secret": "yyy"
        ] as [String : Any]

    let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])

    var request = URLRequest(url: URL(string: "http://xxx.xxx")! as URL,
                                      cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = postData

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in
        guard let data = data else {
          completion(nil,error)
          return
        }
        do{
            try validate(response)
            let json = try JSONSerialization.jsonObject(with: data, options: [])
            completion(json,nil)

        }catch{
            print(error)
            completion(nil,error)
        }
        //print(String(describing: data))
    }

    dataTask.resume()
}

调用

httpPost { (json,error) in
   print(json)
}

最好将 json 转换为 [Any]/[String:Any] 分别用于 Array/Dictionary 响应

关于ios - 快速从http请求中检索json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52910406/

相关文章:

ios - 将 Tapku 库添加到 iOS 项目 - 链接器错误

ios - 如何在 Xcode 6 Interface Builder 中使用模板渲染模式?

ios - 自定义 UITableViewCell heightForRowAt 在 Swift 4 中不起作用

ios - 在 iPhone6 设备上运行我的应用程序时出现错误

ios - tableview平滑滚动最佳实践swift

ios - Swift:init中super.init和self.attribute的顺序

ios - 一旦 UIApplication.SharedApplication.OpenUrl 加载了 Web 链接,MonoTouch 会发出通知

ios - UISlider子类: CGContextAddPath: invalid context 0x0

ios - 将场景锁定到 Sprite 节点 swift xcode

json - 尝试使用 Swift 中的 Json token 从服务器获取身份验证