美文网首页
Note 14 简单的http请求与tableView

Note 14 简单的http请求与tableView

作者: cry_0416 | 来源:发表于2016-08-02 20:56 被阅读24次

将获得的数据处理然后写入tableview里

import UIKit

class ViewController: UIViewController,UITableViewDataSource ,UITableViewDelegate{

    var dSource :Array<String> = []
    var tableView : UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        getSource()
        let image = UIImage(named: "pict1")
        let viewHead = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
        viewHead.image = image
        tableView = UITableView(frame: self.view.bounds, style: .Plain)
        tableView.dataSource = self
        tableView.delegate = self
        //tableView头部添加图片
//        tableView.tableHeaderView = viewHead
        tableView.headerViewForSection(0)
        
        self.view.addSubview(tableView)
 
    }
    //行数
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return dSource.count
        
    }
    //构建cell
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        var cell = tableView.dequeueReusableCellWithIdentifier("Cell")
        if cell == nil{
            cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell")
        }
        cell?.textLabel?.text = dSource[indexPath.row]
        return cell!
    }
    //选中cell的时候触发的事件
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print(dSource[indexPath.row])
    }
    //section的头部view设置//titleForHeaderInSection是改变文字//footer同理
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let image = UIImage(named: "pict1")
        let viewHead = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
        viewHead.image = image
        return viewHead
    }
    //设置seciton的头部高度,不设置第一个section会被隐藏
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }
    
    //获取tableview的datasource
    func getSource(){

        let listPath = "https://gitshell.com/wcrane/FM-Res/raw/blob/master/channels.json"
        
        let url = NSURL(string: listPath)!
        let taks = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in

            //这里的error只是网络请求是否出错
            if let _ = error {
                //error不是空的,表示网络出错
                print(error?.localizedDescription)
            }else
                if let httpresponse = response as? NSHTTPURLResponse{
                    //服务器有响应
                    print("i have respone")
                    if httpresponse.statusCode == 404{
                        //404表示not found,url对应资源不存在
                        print("404")
                    }else
                        if httpresponse.statusCode == 200{
                            //200表示成功
                            if let d = data{
                                //判断data里是否有数据,收到的数据是NSdata类型
                                //NSJSONSerialization.JSONObjectWithData//转化成json格式
                                let arr = try! NSJSONSerialization.JSONObjectWithData(d, options: .AllowFragments) as? Array<NSDictionary>
                                for dict in arr! {
                                    //定义了一个类去整理json的数据
                                    let ch = channelMode(dict:dict)
                                    self.dSource.append("\(ch.channel_name)-\(ch.channel_id)")
                                }
                                print("before,refresh",NSThread.isMainThread())
                                //让self.refresh(更新数据)方法回到主线程,进行数据的更新//更新必须在主线程
                                self.performSelectorOnMainThread(#selector(self.refresh), withObject: nil, waitUntilDone: true)
                            }
                        }
                }
        }
        //执行请求
        taks.resume()
    }
    
    //更新数据
    func refresh(){
        print("refresh",NSThread.isMainThread())
        tableView.reloadData()
    }
    

}

创建http请求后,别忘了用resume()

task.resume()

简单的流程就是:

网络请求是否出错(error是否为nil)

服务器有没有响应(let httpResponse = response as? NSHTTPURLResponse)

判断状态码(httpResponse.statusCode == 200) 200就是成功

判断接受的data是否有数据(let d = data 判断data是否有数据)

因为收到的数据是NSdata类型,所以要将它变成json格式

NSJSONSerialization.JSONObjectWithData(d, options: .AllowFragments) as? Array<NSDictionary> //这个网址给的数据是数组,数组里面的元素是字典类型

我定义了一个类去处理这里面的json格式,拿需要的数据

class channelMode{
    var channel_name: String!
    var channel_id: String!
    var chaUrl: NSURL!
    init(dict: NSDictionary){
        
        if let chaID = dict["channel_id"]{
            channel_id = chaID as! String
        }
        
        if let chaName = dict["channel_name"]{
            channel_name = chaName as! String
        }
        
        if  let urlStr = dict["coverUrl"] {
            chaUrl = NSURL(string: urlStr as! String)
        }
        
    }
}

self.dSource.append("\(ch.channel_name)-\(ch.channel_id)")
这样就保存了我们想要的数据,即tableview里的datasource.

UTF8<-->json格式

        //Swift -> JSON
        let dict1 = ["中文", "日文", "英文"]
        //由第二个参数决定是否需要空格、换行之类格式化字符
        let data1 = try! NSJSONSerialization.dataWithJSONObject(dict1, options: [])
        print(data1)
        //转化成json格式
        let jsonStr1 = NSString(data: data1, encoding: NSUTF8StringEncoding)
        //utf8编码转成swift格式
        print(jsonStr1!)

相关文章

网友评论

      本文标题:Note 14 简单的http请求与tableView

      本文链接:https://www.haomeiwen.com/subject/vofqsttx.html