簡體   English   中英

從http請求中快速檢索json數據

[英]Retrieving json data from http request in swift

我是新手,因此是個問題。 我想將我的http調用包裝到此簽名的函數中。

func httpPost()-> Any

該代碼有效,但如何將其包裝在所需的functio簽名中。

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()

我想在這里將json對象返回為Any

在阻塞線程之前,您不能在異步函數中返回直接值,這是一個壞主意,因此您需要完成

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響應

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM