pythonswiftswiftsoup

How to get Api access in Swift?


I have created a program in python where I scrape a value from a 'wind' website. Everything works OK, but I wanted to try to build the same app in Swift, but when I try to run the program, it gives this error: "Unauthorized API access!"

But scraping with python works good... maybe because python uses json? can someone help me to find the mistake in my Swift code?

This is my python WORKING code:

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'])

The output is the wind.

This is my swift code:

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

    }

This gives the API Access error.


Solution

  • for people who want to know the answer:

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