0

我正在测试 XMLParsing 库(使用带有 XML 请求的 Codable 协议)

XMLParsing 库链接: https ://github.com/ShawnMoore/XMLParsing

使用https://openweathermap.org API

API 链接是“ http://api.openweathermap.org/data/2.5/weather

我的模型是

struct weather:Codable {
    let q : String
    let appid : String
    let mode : String
}

并且请求是

        var request = URLRequest(url: URL(string: "http://api.openweathermap.org/data/2.5/weather")!)
        request.httpMethod = "POST"

        let post2 = weather(q: "london", appid: "f4be702b940e5073d765cb2473f0b31b", mode: "xml")


        do{

            let body = try XMLEncoder().encode(post2, withRootKey: "current")

            request.httpBody = body

        } catch{}

        let session = URLSession.shared
        let task = session.dataTask(with: request) { data, response, error in
            if error != nil {
                print("error: \(String(describing: error))")// Handle error…
                return
            }

            guard let data = data else {return }

            print("response: \(response)")
           print("data: \(data)")


    }
        task.resume()

不知道问题出在哪里!我总是收到错误代码 401

response: Optional(<NSHTTPURLResponse: 0x600003bdedc0> { URL: http://api.openweathermap.org/data/2.5/weather } { Status Code: 401, Headers {
    "Access-Control-Allow-Credentials" =     (
        true
    );
    "Access-Control-Allow-Methods" =     (
        "GET, POST"
    );
    "Access-Control-Allow-Origin" =     (
        "*"
    );
    Connection =     (
        "keep-alive"
    );
    "Content-Length" =     (
        107
    );
    "Content-Type" =     (
        "application/json; charset=utf-8"
    );
    Date =     (
        "Mon, 14 Jan 2019 07:14:16 GMT"
    );
    Server =     (
        openresty
    );
    "X-Cache-Key" =     (
        "/data/2.5/weather?"
    );
} })
data: 107 bytes

但在 PostMan 上它工作正常并获取当前数据

在此处输入图像描述

4

1 回答 1

0

感谢@OOPer

我将它作为参数放在链接上并将请求更改为 GET 它现在可以正常工作

import UIKit
import XMLParsing


struct current:Codable {
    let city : City?
}

struct City:Codable {
    let id : String?

}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()




        let request = URLRequest(url: URL(string: "http://api.openweathermap.org/data/2.5/weather?q=london&appid=f4be702b940e5073d765cb2473f0b31b&mode=xml")!)

        let session = URLSession.shared

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



            do{

                guard (error == nil) else {
                    print("There is error")
                    return
                }

                guard let data = data else {return}

                let newData = try XMLDecoder().decode(current.self, from: data)

                print((newData.city?.id)!)

            }catch let error {
                print("there is error",error)
            }

            }
               task.resume()


    }


}
于 2019-01-14T08:46:00.977 回答