在Swift中调用API时遇到问题

时间:2018-12-24 08:21:42

标签: ios swift api urlsession

请检查是否有问题 我有一段代码使用API​​获取电影列表,但是什么也没发生。

    typealias JSONDictHandler = (([String : Any]?) -> Void)
    let session = URLSession(configuration: .default)
    var request = URLRequest(url: URL(string: "http://dev.bsp.vn:8081/training-movie/movie/list")!)

    let token = "dCuW7UQMbdvpcBDfzolAOSGFIcAec11a"
    request.httpMethod = "GET"
    request.setValue(token, forHTTPHeaderField: "app_token")

    let dataTask = session.dataTask(with: request) { (data, response, error) in

        // if nothing wrong
        if error == nil {
            if let httpResponse = response as? HTTPURLResponse {
                switch httpResponse.statusCode {
                case 200: // successful case
                    if let data = data {
                        do {
                            let jsonDict = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)

                            print(jsonDict)

                        } catch let error as NSError {
                            print("Error: \(error.localizedDescription)")
                        }
                    }

                default:
                    print("HTTP Response Code: \(httpResponse.statusCode)")
                }
            }

            // there's something wrong
        } else {
            print("Error: \(String(describing: error?.localizedDescription))")
        }
    }
    dataTask.resume()

此外,我必须在网址中插入一些参数,我该怎么做?

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助!! 允许任意加载为是

enter image description here