如何在Swift中获得API访问权限?

3

我用Python编写了一个程序,从“风”网站上爬取了一些值。一切都运行正常,但我想尝试使用Swift构建相同的应用程序时,运行程序时出现以下错误:“未经授权的API访问!"

但是,使用Python进行抓取很好...也许是因为Python使用JSON?有人能帮我找到Swift代码中的错误吗?

这是我的Python工作代码:

import requests

headers = {'Referer' : 'https://www.windguru.cz/station/219'}    
r = requests.get('https://www.windguru.cz/int/iapi.php?    q=station_data_current&id_station=219&date_format=Y-m-    d%20H%3Ai%3As%20T&_mha=f4d18b6c', headers = headers).json()
print(r)
print(r['wind_max'])

输出就是风。

这是我的Swift代码:

import UIKit
import SwiftSoup

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let myURLString = "https://www.windguru.cz/int/iapi.php?    q=station_data_current&id_station=219&date_format=Y-m-    d%20H%3Ai%3As%20T&_mha=f4d18b6c"
        guard let myURL = URL(string: myURLString) else { return }

        do {
            let myHTMLString = try String(contentsOf: myURL,     encoding: .utf8)
            let htmlcontent = myHTMLString
            print(myHTMLString)

            do {
                let doc = try SwiftSoup.parse(htmlcontent)
                do {
                    let element = try doc.select("title").first()
                }
            }

        }catch let error {
            print("error: \(error)")
        }

    }

这会导致API访问错误。
1个回答

0

对于想要知道答案的人:

override func viewDidLoad() {
    super.viewDidLoad()

    let headers: HTTPHeaders = [
        "Referer" : "https://www.windguru.cz/station/219"
    ]

Alamofire.request("https://www.windguru.cz/int/iapi.php?q=station_data_current&id_station=219&date_format=Y-m-d%20H%3Ai%3As%20T&_mha=f4d18b6c", headers: headers).responseJSON { response in
        debugPrint(response)
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接