"Swift" alamofile network request data Update TableView Pit

Source: Internet
Author: User

Before writing this blog, some words have to mention, only when the hair is angry ...

This afternoon for a alamofire to get data and update tableview problem, check the afternoon of Baidu (360 is the same as hell), unexpectedly did not have a simple and clear answer,

And the only few more close to the answer, said to self.tableView.reloadData() , and did not put the code, said to put in which function,

All still hold the pipa half cover face, let beginners own pit, so depressed an afternoon, just back home, think, or try to try English net, after all, Swift is somebody else's foreigner,

Maybe the foreigner will tell you, how to get data and bind TableView, sure enough, with less than 3 minutes when the perfect solution.

Write this blog, if the next novice lucky to see this, can also take a lot of detours ...

And also

Special thanks to English web

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

有一点特别注意的是,方法 self.tableView.reloadData() 要在变量wifi改变的时候立马加入

Look directly at the following code ...

tableviewcontroller.swift//mytableview-1387////Created by Apiapia on 17/1/6.//copyright©2017 year 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"//},//"Ori Gin ":" 24.127.96.129 ",//" url ":" Http://httpbin.org/get "//}//import uikitimport alamofireimport Swiftyjsonclass Tableviewcontroller:uitableviewcontroller {var wifi = ["StarBuck", "MJ"]//var wifi = [String] () Let URL = "h Ttps://httpbin.org/get "//above WiFi can get remote data with Alamofire,//http://httpbin.org/get override func Viewdidlo The network data obtained by AD () {super.viewdidload ()///Alamofire is asynchronous 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] ()//Regenerate array succeeded//["Accept-language", "Host", "Accept", "User-agent", "Accept-en                        Coding "] for (index,_) in headers{print (index) Self.wifI.append (Index)} self.tableView.reloadData ()        } Case False:print ("Network request Failed")} } print ("WiFi now is:", WiFi)//alamofire.request (URL). Validate (). Responsejson {response in Switch Response.result.isSuccess {//Case true://if let value = RESPONSE.RESULT.V Alue {//Let JSON = JSON (value)//if let number = json[0]["Phones"][0]["number"].str                 ing {////Find phone number//print ("First phone number of first Contact:", No.)//}// }//Case false://Print ("")//}//}//// Registration Form Self.tableView.register (uitableviewcell.self, Forcellreuseidentifier: "Wificell")//Remove empty lines at the end of the table sel F.tableview.tablefootervIew = UIView (Frame:CGRect.zero) Self.tableView.reloadData ()}//MARK:-Table View D ATA Source override func Numberofsections (in Tableview:uitableview), Int {//#warning incomplete implemen Tation, return the number of sections return 3//Total three partitions}//return three partitions corresponding table rows override Func TableView (_ Table View:uitableview, Numberofrowsinsection section:int), Int {//#warning incomplete implementation, return th          E 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 cel L = 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)-&G T            cgfloat {if indexpath.section = = 1 {return}else { Return Super.tableview (TableView, Heightforrowat:indexpath)}}//Deselect highlight direct override Func TableView (_ Tableview:uitableview, Didselectrowat Indexpath:indexpath) {tableview.deselectrow (At:indexpath, animate d:true)}//When you override a static table, use the Indentationlevelforrowat method//Because the data source knows nothing about the newly added cell, so use this proxy method ove Rride Func TableView (_ Tableview:uitableview, Indentationlevelforrowat indexpath:indexpath), Int {i            F 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 Didreceive    Memorywarning () {super.didreceivememorywarning ()//Dispose of any resources the can be recreated.    }/*//Override to support conditional editing of the table view. Override Func TableView (_ Tableview:uitableview, Caneditrowat indexpath:indexpath), Bool {//Return false I        f you don't 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.de Leterows (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 Rearrangin    G 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 I        f you don't want the item to be re-orderable.  return true} */*//MARK:-Navigation//In a storyboard-based application, you'll 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 network request data Update TableView Pit

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.