Make REST API call in Swift

前端 未结 15 1332
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 04:20

I\'m trying to use Swift to make a GET call to a REST API, and have tried to follow numerous tutorials, but can\'t figure it out. Either because I cannot figure out how to

15条回答
  •  北海茫月
    2020-12-02 04:33

    Api Call using Model Class

        let urlString = "http://--.154.--.78/------/index.php?route=api/coupon/all"
    
        let url = URL(string: urlString)
        var request = URLRequest(url: url!)
        request.httpMethod = "GET"
    
        URLSession.shared.dataTask(with:request) { (data, response, error) in
            if error != nil {
                print(error)
            } else {
                do {
    
                    let parsedDictionaryArray = try JSONSerialization.jsonObject(with: data!) as! [String:AnyObject]
                    print(parsedDictionaryArray)
    
                    if let arry = parsedDictionaryArray["data"] as? [[String:AnyObject]] {
                    for dic in arry {
                        let name = dic["name"]
                        let descriptionData = dic["description"]
                        self.modelReference.append(model(name: name as! String, descriptionStr: descriptionData as! String))
                        print(name!)
                    }
                    }
                } catch let error as NSError {
                    print(error)
                }
            }
    
            }.resume()
    

    create a variable and connect with model class

    var modelReference = [model]()
    

    create a model class New -> swift class

    import Foundation
    class model : NSObject{
    var name : String
    var descriptionStr: String
    
    init(name : String, descriptionStr: String)
    {
        self.name = name
        self.descriptionStr = descriptionStr
    }
    

    }

    then we can connect with our table view objects

    let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCellID")as! TableViewCell
        cell.listName.text = modelReference[indexPath.row].name
    

提交回复
热议问题