如何在Swift中访问Api?

2024-04-26 11:09:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python创建了一个程序,从一个“wind”网站上获取一个值。一切正常,但我想尝试建立在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访问错误。你知道吗


Tags: 代码httpsimportwww错误czerrordo
1条回答
网友
1楼 · 发布于 2024-04-26 11:09:41

对于想知道答案的人:

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

相关问题 更多 >