带有Swift标头的URLRequest

时间:2018-01-25 16:14:22

标签: ios json swift

我对Swift相对较新,我在使用swift原生URLRequest从API中提取一些JSON时遇到了麻烦 - 这是在操场上。我测试了API端点,它在Postman

中返回数据就好了

这是我的代码:

//: Playground - noun: a place where people can play
import Foundation
import XCPlayground
import PlaygroundSupport
import UIKit

let urlString = "http://example.test/industry"
let session = URLSession.shared
let url = URL(string: urlString)!
var request = URLRequest(url: url)

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

session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
    if let responseData = response
    {
        do{
            /*let json = try JSONSerialization.jsonObject(with: responseData, options: [])
             print(json)*/
        }catch{
            print("Could not serialize")
        }
    }
})
PlaygroundPage.current.needsIndefiniteExecution = true

我在这里做错了什么?我需要发送标头来从我的端点请求JSON。

1 个答案:

答案 0 :(得分:5)

您必须在.resume()之后添加dataTask{...}

结果,它看起来像这样:

session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
    if let data = data{
        do{
            let json = try JSONSerialization.jsonObject(with: data)
            print(json)
        }
        catch {
            print(error)
        }
    }

}).resume