Friday, January 31, 2020

Azmal Json Get Request with Codable

//
//  GetRequestViewController.swift
//  Api
//
//  Created by Mohammad Azmal Hossain on 1/14/20.
//  Copyright © 2020 Mohammad Azmal Hossain. All rights reserved.
//



import UIKit


struct ResultData: Decodable{
    
    var results: [User]
    
}

struct User: Decodable {
    var gender: String
    var name: Name
}

struct Name: Decodable{
    var title: String
    var first: String
    var last: String
    
}
    // **************************
    
struct WebSiteDescription: Decodable{
    
    let name: String?
    let description: String?
    let courses: [Course]?
}
struct Course: Decodable{
    
    let id: Int?
    let name: String?
    let link: String?
    let imageUrl: String?
    let number_of_lesseons: Int?
}

class GetRequestViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
    
    
    let menuArray = [ "get json Object - Swift 4 = Lets Build That App",
                      "get json Array - Swift 4 = Lets Build That App",
                      "get json Array in Object - Swift 4 = Lets Build That App",
                      "get json Array Missing Fields - Swift 4 = Lets Build That App",
                      "get Json object - Fetch user data & format with URLSession & JSON Decodable!",
                      "post","Arabic", "English", "Bangla", "Malay", "Chinese", "swift guy"]
    
    let menuTableViewCell_Id = "menutableviewCellid"
   

/*

{
    "id"1,
    "name""Instagram Firebase",
    "link""https://www.letsbuildthatapp.com/course/instagram-firebase",
    "imageUrl""https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/04782e30-d72a-4917-9d7a-c862226e0a93",
    "number_of_lessons"49
}

*/
    
    func  getJson_Object_Swift4LetsBuildThatApp_GetRequestApi(){
      //  print("getRequestApi")
         
        let string = "http://api.letsbuildthatapp.com/jsondecodable/course"
        
        guard let url = URL(string: string) else {
            return
        }
        
    URLSession.shared.dataTask(with:  url) { (data, response, err ) in
       //dataTask(with: <#T##URL#>, completionHandler: <#T##(Data?, URLResponse?, Error?) -> Void#>)
         
            // perhaps check err
            // also perhaps check response status 200 ok
        
      
            
        guard let dataUn = data else {
            return
        }
//        let dataAsString = String(data: dataUn, encoding: .utf8)
//            // String(data: <#T##Data#>, encoding: <#T##String.Encoding#>)
//
//        print(dataAsString!)
        
        do {
            
            let course = try
                JSONDecoder().decode(Course.self, from: dataUn)
            print("course --- \(course.name)")
              
        } catch let jsonErr{
            print("error seriatlizing json ", jsonErr)
        }
        
          } .resume()

    }
    

/*
[
    {
        "id"6,
        "name""AppStore JSON APIs",
        "link""https://www.letsbuildthatapp.com/course/AppStore-JSON-APIs",
        "imageUrl""https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/fd78be85-b845-4672-a316-7df0abe80812_medium",
        "number_of_lessons"47
    },
    {
        "id"5,
        "name""Tinder Firestore Swipe and Match",
        "link""https://www.letsbuildthatapp.com/course/Tinder-Firestore-Swipe-and-Match",
        "imageUrl""https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/bc5a4091-d2ea-44ab-b749-5f2ee5354c35_medium",
        "number_of_lessons"47
    },
    {
        "id"1,
        "name""Instagram Firebase",
        "link""https://www.letsbuildthatapp.com/course/instagram-firebase",
        "imageUrl""https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/04782e30-d72a-4917-9d7a-c862226e0a93",
        "number_of_lessons"49
    },
    {
        "id"2,
        "name""Podcasts Course",
        "link""https://www.letsbuildthatapp.com/course/podcasts",
        "imageUrl""https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/32f98d9d-5b9b-4a22-a012-6b87fd7158c2_medium",
        "number_of_lessons"39
    },
    {
        "id"3,
        "name""Intermediate Training Core Data",
        "link""https://www.letsbuildthatapp.com/course/intermediate-training-core-data",
        "imageUrl""https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/0736fecb-5b88-483b-a83d-ca2a5a6d93f9_medium",
        "number_of_lessons"32
    },
    {
        "id"4,
        "name""Kindle Basic Training",
        "link""https://www.letsbuildthatapp.com/basic-training",
        "imageUrl""https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/a6180731-c077-46e7-88d5-4900514e06cf_medium",
        "number_of_lessons"19
    }
]
*/
    
        func  getJson_Array_Swift4LetsBuildThatApp_GetRequestApi(){
          //  print("getRequestApi")
             
            let string = "http://api.letsbuildthatapp.com/jsondecodable/courses"
            
            guard let url = URL(string: string) else {
                return
            }
            
        URLSession.shared.dataTask(with:  url) { (data, response, err ) in
           //dataTask(with: T##URL, completionHandler: <#T##(Data?, URLResponse?, Error?) -> Void#>)
             
                // perhaps check err
                // also perhaps check response status 200 ok
                            
            guard let dataUn = data else {
                return
            }

            
            do {
                
                let courses = try
                    JSONDecoder().decode([Course].self, from: dataUn)
             //   print("courses all code--- \(courses)")
                //print("courses --- \([courses].name)")
                
                for courses in courses {
                    
                    print(courses.id!)
                    print(courses.name!)
                }
                  
            } catch let jsonErr{
                print("error seriatlizing json ", jsonErr)
            }
            
              } .resume()

        }


/*

{
    "name""Lets Build That App",
    "description""Teaching and Building Apps since 1999",
    "courses": [
        {
            "id"1,
            "name""Instagram Firebase",
            "link""https://www.letsbuildthatapp.com/course/instagram-firebase",
            "imageUrl""https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/04782e30-d72a-4917-9d7a-c862226e0a93",
            "number_of_lessons"49
        },
        {
            "id"4,
            "name""Kindle Basic Training",
            "link""https://www.letsbuildthatapp.com/basic-training",
            "imageUrl""https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/a6180731-c077-46e7-88d5-4900514e06cf_medium",
            "number_of_lessons"19
        }
    ]
}
*/
    
    func  getJson_ArrayInObject_Swift4LetsBuildThatApp_GetRequestApi(){
       // print("getRequestApi")
         
        let string = "http://api.letsbuildthatapp.com/jsondecodable/website_description"
        
        guard let url = URL(string: string) else {
            return
        }
        
    URLSession.shared.dataTask(with:  url) { (data, response, err ) in
       // dataTask(with: T##URL, completionHandler: <#T##(Data?, URLResponse?, Error?) -> Void#>)
         
            // perhaps check err
            // also perhaps check response status 200 ok
                    
        guard let dataUn = data else {
            return
        }

        
        do {
            
            let websiteDescription = try JSONDecoder().decode(WebSiteDescription.self, from: dataUn)
            
           // print("description all code--- \(websiteDescription)")
            print(websiteDescription.name)
                  print(websiteDescription.description)
            
            //print("courses --- \([courses].name)")
              
        } catch let jsonErr{
            print("error seriatlizing json ", jsonErr)
        }
        
          } .resume()

    }


/*


[
    {
        "id"1,
        "name""Instagram Firebase",
        "link""https://www.letsbuildthatapp.com/course/instagram-firebase",
        "imageUrl""https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/04782e30-d72a-4917-9d7a-c862226e0a93",
        "number_of_lessons"49
    },
    {
        "id"4,
        "name""Kindle Basic Training",
        "link""https://www.letsbuildthatapp.com/basic-training",
        "imageUrl""https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/a6180731-c077-46e7-88d5-4900514e06cf_medium",
        "number_of_lessons"19
    },
    {
        "name""Yelp"
    }
]

*/

    func  getJson_Array_missing_fields_Swift4LetsBuildThatApp_GetRequestApi(){
       // print("getRequestApi")
         
        let string = "http://api.letsbuildthatapp.com/jsondecodable/courses_missing_fields"
        
        guard let url = URL(string: string) else {
            return
        }
        
    URLSession.shared.dataTask(with:  url) { (data, response, err ) in
       // dataTask(with: T##URL, completionHandler: <#T##(Data?, URLResponse?, Error?) -> Void#>)
         
            // perhaps check err
            // also perhaps check response status 200 ok
                    
        guard let dataUn = data else {
            return
        }

        
        do {
            
            let websiteDescription = try JSONDecoder().decode([Course].self, from: dataUn)
            
           // print("description all code--- \(websiteDescription)")
//            print(websiteDescription.name)
//                  print(websiteDescription.description)
            
            
            //print("courses --- \([courses].name)")
              
        } catch let jsonErr{
            print("error seriatlizing json ", jsonErr)
        }
        
          } .resume()

    }

    func  postRequestApi(){
        
        print("postRequestApi")
        
        
    }
    

/*

{
  "0""#################################################################################################################################",
  "1""#                                                                                                                               #",
  "2""# IMPORTANT - PLEASE UPDATE YOUR API ENDPOINT                                                                                   #",
  "3""#                                                                                                                               #",
  "4""# This API endpoint is deprecated and has now been shut down. To keep using the Fixer API, please update your integration       #",
  "5""# to use the new Fixer API endpoint, designed as a simple drop-in replacement.                                                  #",
  "6""# You will be required to create an account at https://fixer.io and obtain an API access key.                                   #",
  "7""#                                                                                                                               #",
  "8""# For more information on how to upgrade please visit our Github Tutorial at: https://github.com/fixerAPI/fixer#readme          #",
  "9""#                                                                                                                               #",
  "a""#################################################################################################################################"
}
   

*/


    func swiftGuyApiGet(){
        
        let url = URL(string: "http://api.fixer.io/latest")
        
        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error != nil
            {
                print ("ERROR")
            }
            else
            {
                if let content = data
                {
                    do
                    {
                        //Array
                        let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

                        if let rates = myJson["rates"] as? NSDictionary
                        {
                            if let currency = rates["NOK"]
                            {
                                print (currency)
                            }
                        }
                    }
                    catch
                    {
                        
                    }
                }
            }
        }
        task.resume()

        
    }


/*

{
    "results": [
        {
            "gender""female",
            "name": {
                "title""Ms",
                "first""Regina",
                "last""Schultheiß"
            },
            "location": {
                "street": {
                    "number"1809,
                    "name""Kirchgasse"
                },
                "city""Weißenburg-Gunzenhausen",
                "state""Sachsen",
                "country""Germany",
                "postcode"40806,
                "coordinates": {
                    "latitude""-41.8263",
                    "longitude""80.2809"
                },
                "timezone": {
                    "offset""-11:00",
                    "description""Midway Island, Samoa"
                }
            },
            "email""regina.schultheiss@example.com",
            "login": {
                "uuid""cca028fc-5cce-4869-aea8-e9ae40b21c73",
                "username""lazytiger620",
                "password""passwor",
                "salt""UU4IALN5",
                "md5""82fef34128ac0cdd9fa499a74c4c9633",
                "sha1""cb8016b70afa6b6eb4efaa557bdef168df37bedc",
                "sha256""516f9ba3160c6be56ed616e2bc00e5bd40533c7904db89036ae8ac291a054b53"
            },
            "dob": {
                "date""1981-05-27T15:26:44.071Z",
                "age"39
            },
            "registered": {
                "date""2017-12-28T03:08:47.277Z",
                "age"3
            },
            "phone""0071-1742128",
            "cell""0171-2870107",
            "id": {
                "name""",
                "value"null
            },
            "picture": {
                "large""https://randomuser.me/api/portraits/women/29.jpg",
                "medium""https://randomuser.me/api/portraits/med/women/29.jpg",
                "thumbnail""https://randomuser.me/api/portraits/thumb/women/29.jpg"
            },
            "nat""DE"
        }
    ],
    "info": {
        "seed""63b987c48613d80d",
        "results"1,
        "page"1,
        "version""1.3"
    }
}
*/


    func fetchUser(amount: Int){
        
        guard let url: URL = URL(string: "https://randomuser.me/api/") else {
            return
        }
        
        URLSession.shared.dataTask(with: url) { (data, res, erra) in
        
            if let erra = erra {
                print("erra \(erra)")
            }
            guard let data = data else {
                return
            }
            
            do {
                
                let getData = try JSONDecoder().decode(ResultData.self, from: data)
                
                print("response \(getData)")
                print("getData1 \(getData.results[0])")
                print("getData2 \(getData.results[0].gender)")
                print("getData3 \(getData.results[0].name)")
                print("getData4 \(getData.results[0].name.first)")
                
                let userName = getData.results[0].name
                print("hi", userName.title, userName.first, userName.last, "my name is ")
            }catch let erra {
                print("catch erra \(erra)")
            }
        }.resume()
//        URLSession.shared.dataTask(with: url) { data, res,erra in
//
//            if let erra = erra {
//                print("error \(erra)")
//            }
//            guard let data = data else {
//                return
//            }
//            print("data \(data)")
//
//            do {
//
//                let response = try JSONDecoder().decode(ResultData.self, from: data)
//                print("response \(response)")
//            } catch erra{
//                print(erra)
//            }
//        }.resume()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        setup()
        
    }
    
    

    
    
    let menuTableView: UITableView = {
        
        let tableView = UITableView()
        tableView.backgroundColor = .lightGray
        tableView.translatesAutoresizingMaskIntoConstraints = false
        return tableView
    }()
    
    func setup(){
        
        

        
        
        menuTableView.dataSource = self
        menuTableView.delegate = self
        
        self.view.addSubview(menuTableView)
        
        menuTableView.register(UITableViewCell.self, forCellReuseIdentifier: menuTableViewCell_Id)
        
        menuTableView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
        menuTableView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 0).isActive = true
        menuTableView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: 0).isActive = true
        menuTableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0).isActive = true
        
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return menuArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: menuTableViewCell_Id, for: indexPath)
        
        cell.textLabel?.text = menuArray[indexPath.row]
        cell.textLabel?.numberOfLines = 0
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.row == 0 {

            getJson_Object_Swift4LetsBuildThatApp_GetRequestApi()

        } else if indexPath.row == 1{
            
           getJson_Array_Swift4LetsBuildThatApp_GetRequestApi()
            
        } else if indexPath.row == 2{
            
                   getJson_ArrayInObject_Swift4LetsBuildThatApp_GetRequestApi()
            
               }else if indexPath.row == 3{
               
                      getJson_Array_missing_fields_Swift4LetsBuildThatApp_GetRequestApi()
               
        } else if indexPath.row == 4 {
            
            fetchUser(amount: 0)
            
        }

        
        else if indexPath.row == 8 {
            
            swiftGuyApiGet()
            
        }
    }
    
}