Skip to main content

JSON Parsing with Codable in Swift - Nested JSON Model

#Swift, to supporting decoding and encoding we must adopt the #NSCoding protocol and implement its methods. 

#Apple has introduced a new way to decode and encode the #JSON data using with Codable since Swift 4. 

You need to consume the following API to search and display images. - Flickr

Https://www.flickr.com/services/api/flickr.photos.search.htm The API results in search results for a

Documentation on this page to get the image URLS:

https://www.flickr.com/services/api/misc.urls.html

XXXXXXXX - API Key

Open Test Api - https://api.flickr.com/services/rest/?method=flickr.galleries.getPhotos&api_key=XXXXXXXX&gallery_id=66911286-72157647277042064&format=json&nojsoncallback=1


Model: - 

import Foundation


struct ResponseCodable : Codable {

    let photos : Photos?

    let stat : String?


    enum CodingKeys: String, CodingKey {


        case photos = "photos"

        case stat = "stat"

    }


    init(from decoder: Decoder) throws {

        let values = try decoder.container(keyedBy: CodingKeys.self)

        photos = try values.decodeIfPresent(Photos.self, forKey: .photos)

        stat = try values.decodeIfPresent(String.self, forKey: .stat)

    }


}


struct Photos : Codable {

    let page : Int?

    let pages : Int?

    let perpage : Int?

    let total : Int?

    let photo : [Photo]?


    enum CodingKeys: String, CodingKey {


        case page = "page"

        case pages = "pages"

        case perpage = "perpage"

        case total = "total"

        case photo = "photo"

    }


    init(from decoder: Decoder) throws {

        let values = try decoder.container(keyedBy: CodingKeys.self)

        page = try values.decodeIfPresent(Int.self, forKey: .page)

        pages = try values.decodeIfPresent(Int.self, forKey: .pages)

        perpage = try values.decodeIfPresent(Int.self, forKey: .perpage)

        total = try values.decodeIfPresent(Int.self, forKey: .total)

        photo = try values.decodeIfPresent([Photo].self, forKey: .photo)

    }


}


struct Photo : Codable {

    let id : String?

    let owner : String?

    let secret : String?

    let server : String?

    let farm : Int?

    let title : String?

    let ispublic : Int?

    let isfriend : Int?

    let isfamily : Int?

    let is_primary : Int?

    let has_comment : Int?


    enum CodingKeys: String, CodingKey {


        case id = "id"

        case owner = "owner"

        case secret = "secret"

        case server = "server"

        case farm = "farm"

        case title = "title"

        case ispublic = "ispublic"

        case isfriend = "isfriend"

        case isfamily = "isfamily"

        case is_primary = "is_primary"

        case has_comment = "has_comment"

    }


    init(from decoder: Decoder) throws {

        let values = try decoder.container(keyedBy: CodingKeys.self)

        id = try values.decodeIfPresent(String.self, forKey: .id)

        owner = try values.decodeIfPresent(String.self, forKey: .owner)

        secret = try values.decodeIfPresent(String.self, forKey: .secret)

        server = try values.decodeIfPresent(String.self, forKey: .server)

        farm = try values.decodeIfPresent(Int.self, forKey: .farm)

        title = try values.decodeIfPresent(String.self, forKey: .title)

        ispublic = try values.decodeIfPresent(Int.self, forKey: .ispublic)

        isfriend = try values.decodeIfPresent(Int.self, forKey: .isfriend)

        isfamily = try values.decodeIfPresent(Int.self, forKey: .isfamily)

        is_primary = try values.decodeIfPresent(Int.self, forKey: .is_primary)

        has_comment = try values.decodeIfPresent(Int.self, forKey: .has_comment)

    }


}


Request method:-


        var photoList = [Photo]()



        if let url = URL(string: urlString) {

            if let data = try? Data(contentsOf: url) {

                // we're OK to parse!

                parse(json: data)

            }

        }




func parse(json: Data) {

        let decoder = JSONDecoder()

        do{

            let jsonPetitions = try decoder.decode(ResponseCodable.self, from: json)

            print(jsonPetitions)

            let dataInfo = jsonPetitions.photos?.photo

            photoList = dataInfo!

        }catch{

            print(error.localizedDescription)

        }

    }

Comments

Popular posts from this blog

Add a Scene Delegate to your existing project with Storyboard in Swift

To add a scene delegate, first, create a new Swift file that you’ll call "SceneDelegate" containing a subclass of UIResponder, just like the AppDelegate, and that conforms to UIWindowSceneDelegate.  As your app might supports other versions than iOS 13, make this class only available for iOS 13. This is what you should have : If you are working a project that is storyboard based, please set storyboard  initial view controller SceneDelegate.swift import UIKit @available ( iOS 13.0 , *) class SceneDelegate : UIResponder , UIWindowSceneDelegate {     var window : UIWindow ?     func scene ( _ scene: UIScene , willConnectTo session: UISceneSession , options connectionOptions: UIScene . ConnectionOptions ) {                  let storyboard = UIStoryboard (name: "Main" , bundle: nil )         let initialViewController = storyboard. instantiateViewController (withIdentifier: "ViewController" )         let mainNavigationController = UINavigationControlle

How Create Animated Circle Progress Bar iOS 11 Swift 4

  Animated Circle Progress Bar iOS 11 Swift 4 With MBCircularProgressBa r - https://github.com/MatiBot/MBCircularProgressBar A circular, animatable & highly customizable progress bar from the Interface Builder Swift, Using pod fite MBCircularProgressBar Installation Cocoapods terminal. pod "MBCircularProgressBar" That - A Simple Steps to installed pod file -        Open terminal        Command on terminal go to project folder Cd path        set your project path on terminal.        command : pod init        open pod file - open -e podfile        added in pod file with in : pod "MBCircularProgressBar"        Command : Pod install        Close project of Xcode        open your Project from terminals        Command : open PodDemos.xcworkspace After opern StoryBoard and Now drag a UIView over the viewController in storyboard Or set UIView Constraint width, height or verticle or horzentail space and set a class MBCircul

How to Use Multiple Sections in UITableView iOS Swift !

Multiple sections in UITableView iOS Swift. UITableView is very important part of iOS ecosystem. So we split tableviews in sections. Then its easier to find right information.  1. First let’s create a project as usual. Create a new single view application X code project. Set project name to UIViewController.  2. Go to main storyboard & select view controller & use UITableView 3. Select tableview & make it initial view controller  4 Create a custom Sections Class like Name => TableSections, create register cell static return “ getCellNibs ” method. Then create  4 section enum “TableItems” then after append all sections to an array model. import UIKit struct CellNib {      static func getCellNibs () -> [ String ] {          return [ "Cell1" , "Cell2" , "Cell3" , "Cell4" ]     } } enum TableItems : Int {      case TableSections1      case TableSections2      case TableSections3      case TableSections4 } class TableSec