ទាញ data ពី API ដាក់ TableView xcode

នៅមេរៀនយើងបានសិក្សារួចមកហើយ ដោយយើងទាញ data json ជា API ។ ឥឡូវនេះយើងមកសិក្សា data api ជាមួយ tableView

បង្កើត folder ថ្មីមួយ (New Group) រួចហើយដាក់ឈ្មោះថា Model => បន្ទាប់មកបង្កើត file swift ថ្មីមួយដោយយើងដាក់ឈ្មោះ Contact ដើម្បីផ្ទុក property នៃ variable

import Foundation
class Contact{
    var name: String
        var sex: String
        var phone: String
        
        init(name: String, sex: String, phone: String){
            self.name = name
            self.sex = sex
            self.phone = phone
        }
     
}

  • បង្កើត folder ថ្មីមួយ (New Group) រួចហើយដាក់ឈ្មោះថា Service => បន្ទាប់មកបង្កើត file swift ថ្មីមួយដោយយើងដាក់ឈ្មោះ ContactServices និងបង្កើត class

    import Foundation
    class ContactService{
        
    }
    

    បង្កើត function មួយដោយយើងដាក់ឈ្មោះថា getContact ដែលមាន parameter ពីរ

    import Foundation
    class contactService{
        
        func getContact(){
            
        }
    }
    

    សរសេរកូដដើម្បីចាប់យក API

    import Foundation
    class ContactService{
        let URL_GET_CONTACT = "https://script.google.com/macros/s/AKfycby8gUI56dyvtSjUQjyZ9AaatT4AWBgIznyqt203dFv39AtYxPJ_5wTAyBHfSchypC8Yaw/exec"
        func getContact(name: String, phone: String, sex: String){
            let url = URL(string: URL_GET_CONTACT)
            URLSession.shared.dataTask(with: url!) { data, response, error in
                if error == nil{
                    let jsonObject = try? JSONSerialization.jsonObject(with: data!, options: .fragmentsAllowed)
                    let dict = jsonObject as! [String: Any]
                    
                    if dict["status"] as! Int == 200{
                        let data = dict["data"] as! NSArray
                        //បង្កើត variable មួយសំរាប់ចាប់ទិន្ន័យ Contact រសប់ model
                        var contacts = [Contact]()
                        for d in data{
                            let a = d as! [String: Any]
                            
                            let name = a["NAME"] as! String
                            let phone = a["PHONE"] as! String
                            let sex = a["SEX"] as! String
                            
                            // map ជាមួយ model
                            let contact = Contact(name: name, sex: sex, phone: phone)
                            
                            contacts.append(contact)
                        
                        }
                        print(contacts.count)
                    }
                    
                }
            }.resume()
        }
    }
    

  • variable url ដាក់អក្សរធំគឺ Intent គឺកែអត់កើត

    ដើម្បីឲ្យកូននឹង print ទៅវាដើរយើងត្រូវហៅ ឬ implement នៅក្នុង viewDidload()
    import UIKit
    
    class ViewController: UIViewController {
    
        var contactService: ContactService!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            let contactService = ContactService()
            
            contactService.getContact(name: "NAME", phone: "PHONE", sex: "SEX")
         
        }
    
    
    }
    
    

    យើងធ្វើបានប៉ុន្នឹងហើយ ប៉ុន្តែយើងមិនអាចហៅ data ពី class ContactService មកប្រើបានទេ។ ដោយយើងត្រូវតែប្រើ function មួួយគឺ encaping closure ដោយយើងប្រើនៅក្នុង function getContact ដើម្បីបោះទិន្ន័យតាមវា

    អ្វីទៅ encaping closure គឺជា closure ដែលយើងប្រើ closure ជា parameter របស់ fucntion និងវាដើរឬហៅនៅពេលដែលការងារមួយដើរចប់ ឬ function មួយដើរចប់។

    syntax
     
    (name parameter @escaping()->Void)
    // មាន parameter 
    (name parameter @escaping(_ nameparet: [datatype])->Void)
    
    import Foundation
    class ContactService{
        let URL_GET_CONTACT = "https://script.google.com/macros/s/AKfycby8gUI56dyvtSjUQjyZ9AaatT4AWBgIznyqt203dFv39AtYxPJ_5wTAyBHfSchypC8Yaw/exec"
        func getContact(name: String, phone: String, sex: String, handle: @escaping(_ contact: [Contact])->Void){
            let url = URL(string: URL_GET_CONTACT)
            URLSession.shared.dataTask(with: url!) { data, response, error in
                if error == nil{
                    let jsonObject = try? JSONSerialization.jsonObject(with: data!, options: .fragmentsAllowed)
                    let dict = jsonObject as! [String: Any]
                    
                    if dict["status"] as! Int == 200{
                        let data = dict["data"] as! NSArray
                        //បង្កើត variable មួយសំរាប់ចាប់ទិន្ន័យ Contact រសប់ model
                        var contacts = [Contact]()
                        for d in data{
                            let a = d as! [String: Any]
                            
                            let name = a["NAME"] as! String
                            let phone = a["PHONE"] as! String
                            let sex = a["SEX"] as! String
                            
                            // map ជាមួយ model
                            let contact = Contact(name: name, sex: sex, phone: phone)
                            
                            contacts.append(contact)
                        }
                        handle(contacts)
                    }
                }
            }.resume()
        }
    }
    

    យើងបោះទិន្ន័យទៅ model តាមរយៈ escaping "@escaping(_ contact: [Contact])->Void){"

    យើងមកសិក្សានៅខាង ViewController យើងវិញម្តង។ ដោយយើងហៅទិន្ន័យចេញពី Model មកប្រើ

    បោះទិន្ន័យចូលទៅក្នុង TableView

    យើងបង្កើត tableView

    import UIKit
    
    class ViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {
       
    
        @IBOutlet weak var tableView: UITableView!
        
        var contactService: ContactService!
        //បង្កើត variable ចំទទួលទិន្ន័យ escaping
        var contacts = [Contact]()
        
        override func viewDidLoad() {
            super.viewDidLoad()
            let contactService = ContactService()
            
            contactService.getContact(name: "NAME", phone: "PHONE", sex: "SEX") { contact in
                //ដោះទិន្ន័យចូល varaible ទុកប្រើជាមួយ table
                self.contacts = contact
                
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
              
            }
         
        }
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return contacts.count
        }
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
            cell?.textLabel?.text = contacts[indexPath.row].phone
            cell?.detailTextLabel?.text = contacts[indexPath.row].name
            
            cell?.textLabel?.font = UIFont.systemFont(ofSize: 22.0)
            cell?.detailTextLabel?.font = UIFont.systemFont(ofSize: 20.0)
            
            return cell!
        }
        
    }
    
  • Post a Comment

    0 Comments