【Swift】Alamofile網路請求資料更新TableView的坑

來源:互聯網
上載者:User

標籤:select   ict   move   sources   mem   specified   ram   water   open   

 

寫這篇BLOG前,有些話不得不提一下,就僅當發發惱騷吧。。。

今天下午為了一個Alamofire取得資料而更新TableView的問題,查了一下午的百度(360也是見鬼的一樣),竟然沒有一個簡單明了的回答,

而唯一幾個比較接近答案的,說要 self.tableView.reloadData(),也沒有貼上代碼,說要放在哪個函數內,

都猶抱琵琶半遮面,讓初學者自己采坑,於是鬱悶了一下午,剛剛回到家,試想想,要不試試英文網,畢竟Swift就是人家老外的,

說不定老外會告訴你,怎麼取得資料並綁定TableView,果不其然,用了不到3份鐘的時候就完美解決。

寫這篇BLOG,如果後面的新手有幸看到這篇,也可以少走很多彎路。。。

還有

特別感謝英文網

http://blog.revivalx.com/2015/02/23/uitableview-tutorial-in-swift-using-alamofire-haneke-and-swiftyjson/

 

有一點特別注意的是,方法 self.tableView.reloadData() 要在變數wifi改變的時候立馬加入

直接看以下的代碼了。。。

 

 

////  TableViewController.swift//  MyTableView-1387////  Created by apiapia on 17/1/6.//  Copyright © 2017年 apiapia. All rights reserved.//$ curl http://httpbin.org/get////{//    "args": {},//    "headers": {//        "Accept": "*/*",//        "Connection": "close",//        "Content-Length": "",//        "Content-Type": "",//        "Host": "httpbin.org",//        "User-Agent": "curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3"//    },//    "origin": "24.127.96.129",//    "url": "http://httpbin.org/get"//}//import UIKitimport Alamofireimport SwiftyJSONclass TableViewController: UITableViewController {    var  wifi = ["StarBuck","MJ"]    // var wifi = [String]()     let url = "https://httpbin.org/get"    //上面wifi可以用 Alamofire擷取遠端資料,    //http://httpbin.org/get                override func viewDidLoad() {        super.viewDidLoad()                         //  Alamofire取得的網路資料是非同步        Alamofire.request(url, method: .get).validate().responseJSON { (response) in          //  print (response.request)            switch response.result.isSuccess {            case true:                                if let value =  response.result.value  {                    let json = JSON(value)                                      let headers:Dictionary<String,Any>=json["headers"].dictionaryValue                                        print (headers)                   // populating tableview with json from url using Alamofire                   //  http://blog.revivalx.com/2015/02/23/uitableview-tutorial-in-swift-using-alamofire-haneke-and-swiftyjson///                    self.wifi = ["1","2","3","4"]//                    self.tableView.reloadData()                                       self.wifi = [String]() // 重建數組成功                  //  ["Accept-Language", "Host", "Accept", "User-Agent", "Accept-Encoding"]                    for (index,_) in headers{                                                print (index)                        self.wifi.append(index)                                            }                    self.tableView.reloadData()                                    }                         case false:                print ("網路請求失敗")                            }        }               print ("wifi現在是:",wifi)        //        Alamofire.request(url).validate().responseJSON { response in//            switch response.result.isSuccess {//            case true://                if let value = response.result.value {//                    let json = JSON(value)//                    if let number = json[0]["phones"][0]["number"].string {//                        // 找到電話號碼//                        print("第一個連絡人的第一個電話號碼:",number)//                    }//                }//            case false://                print("")//            }//        }//                       //註冊表格        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "wifiCell")        //去掉表格尾部空行        self.tableView.tableFooterView = UIView(frame: CGRect.zero)                self.tableView.reloadData()                 }      // MARK: - Table view data source    override func numberOfSections(in tableView: UITableView) -> Int {        // #warning Incomplete implementation, return the number of sections        return 3 //共有三個分區     }    //返回三個分區相應的表格行數    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        // #warning Incomplete implementation, return the number of rows          if section == 1 {                         return self.wifi.count                       }          else{            return 1                      }                }       override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {                if indexPath.section == 1 {            let cell = tableView.dequeueReusableCell(withIdentifier: "wifiCell", for: indexPath)            cell.textLabel?.text = self.wifi[indexPath.row]                        return cell        }else{            return super.tableView(tableView, cellForRowAt: indexPath)        }                           }        override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {                if indexPath.section == 1 {                        return 50                    }else {            return super.tableView(tableView, heightForRowAt: indexPath)        }    }        //取消高亮直選    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {                tableView.deselectRow(at: indexPath, animated: true)    }     // 當 override了一個靜態表格的時候要用到 indentationLevelForRowAt這個方法     // 因為 資料來源 對新加進來的 cell一無所知 ,所以要用這個代理方法    override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {                if indexPath.section == 1 {                        let newIndexPath = IndexPath(row: 0, section: indexPath.section)            return super.tableView(tableView, indentationLevelForRowAt:  newIndexPath)                                            }else {                        return super.tableView(tableView, indentationLevelForRowAt: indexPath)        }    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }                                /*    // Override to support conditional editing of the table view.    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {        // Return false if you do not want the specified item to be editable.        return true    }    */    /*    // Override to support editing the table view.    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {        if editingStyle == .delete {            // Delete the row from the data source            tableView.deleteRows(at: [indexPath], with: .fade)        } else if editingStyle == .insert {            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view        }        }    */    /*    // Override to support rearranging the table view.    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {    }    */    /*    // Override to support conditional rearranging of the table view.    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {        // Return false if you do not want the item to be re-orderable.        return true    }    */    /*    // MARK: - Navigation    // In a storyboard-based application, you will often want to do a little preparation before navigation    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {        // Get the new view controller using segue.destinationViewController.        // Pass the selected object to the new view controller.    }    */}



 

【Swift】Alamofile網路請求資料更新TableView的坑

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.