Old article (Swift3) is here Getting JSON from the API using Alamofire
#Xcode 10.1
#Swift 4.2
This is a sample to get information from the weather API using Alamofire, a famous swift communication library, and SwiftyJSON, a famous swift JSON library.
In this sample, the JSON is acquired asynchronously and an alert is displayed.
Don't forget to set up the ATS as well.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import Alamofire | |
import SwiftyJSON | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.backgroundColor = UIColor.white | |
//お天気APIから東京の天気を取得する | |
let url: String = "http://weather.livedoor.com/forecast/webservice/json/v1?city=130010" | |
Alamofire.request(url, method: .get, encoding: JSONEncoding.default).responseJSON { response in | |
switch response.result { | |
case .success: | |
let json: JSON = JSON(response.result.value ?? kill) | |
print(json) | |
self.showWeatherAlert(title: json["title"].stringValue, message: json["description"]["text"].stringValue) | |
case .failure(let error): | |
print(error) | |
} | |
} | |
} | |
func showWeatherAlert(title: String, message: String) -> Void { | |
// アラートを作成 | |
let alert = UIAlertController( | |
title: title, | |
message: message, | |
preferredStyle: .alert) | |
alert.addAction(UIAlertAction(title: "OK", style: .default)) | |
// アラート表示 | |
self.present(alert, animated: true, completion: nil) | |
} | |
} |