I'm trying to make a request (GET) to a REST API. This API returns airport weather reports in JSON format.
What I am trying to achieve is the following: The user inputs the identification code of an airport, which gets amended to the url. When he/she presses the 'Request' button, a GET request is made to the API which will then show the result in a UILabel.
I've come so far as being able to make the call using a button, and the response from the server is being printed in the console, but I can't get it printed in the UILabel.
This is my code so far:
//
// ViewController.swift
// urltest
//
// Created by Stefan Oomen on 06/05/2020.
// Copyright © 2020 FlyTechSoft. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var metarResponse: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
@IBAction func onButtonClick(_ sender: UIButton) {
let url = URL(string: "hhttps://website.rest/api/metar/location?options=&airport=true&reporting=true&format=json&onfail=cache")!
var request = URLRequest(url: url)
request.addValue("My_API_KEY", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let response = response {
print(response)
if let data = data, let body = String(data: data, encoding: .utf8) {
print(body)
}
} else {
print(error ?? "Unknown error")
}
}
task.resume()
}
}
In the GET URL I only need to change the 'Location?' portion, using the input from the user from the 'icaoTextField' UITextField:
https://website.rest/api/metar/location?options=&airport=true&reporting=true&format=json&onfail=cache
I'm quite new to this, so all help is very welcome. Thank you! PS. Small subquestion: is it possible to select and use only specific portions of a REST API call's result?