iOS Tutorials: Extract JSON from API and load information with image

OVERVIEW

Application Programming Interface (API) is a set of function and procedures that allow creation of application to access features or data application of other services. We will be accessing data from NewsAPI hoping to extract latest news from the site via the API provided and paste it on our app along with the image downloaded.

THIRD PARTY LIBRARY

Before we began, we will be using the Cocoapods to utilize the third party libraries. Some of the libraries that will be used are Alamofire, SwiftyJSON and Kingfisher. If you have no idea how to use Cocoapods, check out my other tutorial on installing it first.

Let’s began by creating a new Swift File and name is Extras. Inside the file, I will be storing the URL with the API Key. You are required to use your own API which you can get from NewsAPI. The following code is a syntax to create closure. It doesnt have any paramter types nor are we returning anything hence the empty parentheses. Typealias is just a way of renaming an existing type. Check my other tutorial of me explaining What is typealias?

let API_URL = "https://newsapi.org/v2/top-headlines?country=my&apiKey=<YOUR-API-KEY>"

typealias DownloadComplete = () -> ()

In the next step, create another Swift File and name it News. Here we will be creating a new function of downloading the content. What the code below means:

  • We name our closure completed and include our custom closure DownloadComplete.
  • We use @escaping which is often used in asynchronous operation like web request.
func downloadNews(completed: @escaping DownloadComplete) {

}

Extracting JSON from API

This is easily done with the help of SwiftyJSON and Alamofire but first we need to be aware of the kind of JSON file that we will be reading

{
"status": "ok",
"totalResults": 20,
-"articles": [
-{
-"source": {
"id": null,
"name": "Theedgemarkets.com"
},
"author": null,
"title": "Ananda Krishnan among 18 named in India's Central Bureau of Investigation chargesheet",
"description": "KUALA LUMPUR (July 20): Malaysian tycoon T. Ananda Krishnan is among the 18 named in India’s Central Bureau of Investigation's (CBI) chargesheet for the Aircel-Maxis case, The Economic Times reported.The Economic Times quoted the CBI as saying in the chargesh…",
"url": "http://www.theedgemarkets.com/article/ananda-krishnan-among-18-named-indias-central-bureau-investigation-chargesheet",
"urlToImage": "https://assets.theedgemarkets.com/krishnan_20180720150145_bloomberg.jpg?null",
"publishedAt": "2018-07-20T06:59:53Z"
},


We could easily extract the data from the JSON by the following code if we understand the structure of the JSON as shown above.

    func downloadNews(completed: @escaping DownloadComplete) {
        Alamofire.request(API_URL).responseJSON { (response) in
            let result = response.result
            let json = JSON(result.value)
            
            self._name = json["articles"][1]["source"]["name"].stringValue
            
            self._author = json["articles"][1]["author"].stringValue
            
            self._title = json["articles"][1]["title"].stringValue
            
            self._short = json["articles"][1]["description"].stringValue
            
            self._image = json["articles"][1]["urlToImage"].stringValue
            
            completed()
        }
    }

Show Data on UI

Now, we would like the data to be shown on our UI. In my case, I’ve created a UI with ImageView and three Label. I’ve created a variable of News type so that I could assign the value to the respective outlet.

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var authorLabel: UILabel!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var shortLabel: UILabel!
    
    var news: News!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        news = News()
        news.downloadNews {
            DispatchQueue.main.async {
                self.updateUI()
            }
        }
    }
    
    func updateUI(){
        let url = URL(string: news.image)
        imageView.kf.setImage(with: url)
        authorLabel.text = news.name
        titleLabel.text = news.title
        shortLabel.text = news.short
    }


}

In the end it would look like below with the image downloaded using KingFisher. If you see some blank, it means the value is nil. The code can be downloaded from Github

  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*