Skip to content

Obtaining JSON from the API using Alamofire

   

New article (Swift4) is here. Using Alamofire to get JSON from the API (Swift4.2)

This is a sample of retrieving information from the weather API using Alamofire, a famous swift communication library, and SwiftyJSON, another famous swift library for JSON.
In this sample, the JSON is acquired asynchronously and an alert is displayed.

Translated with www.DeepL.com/Translator (free version)

Reference:
Alamofire
お天気API

import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//お天気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["title"])
print(json["description"]["text"])
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)
}
}

  1. Calling a method from another View in a delegate
  2. Get and display the class name, function name and line number in Swift
  3. Selecting images with UIImagePickerController
  4. Playing music with Swift
  5. Array(Ruby)
  6. Whitening the UIStatusBar
  7. UITableView and UISearchBar