• Swift


    使用NSURLConnection.sendAsynchronousRequest()可以采用异步获取的方式取得数据。下面通过对数据获取类进行封装,演示如何进行数据请求与接收。


    1,HttpController.swift (数据获取封装类,结果处理协议)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    import UIKit
     
    //自定义http协议
    protocol HttpProtocol{
        //定义一个方法接收一个字典
        func didRecieveResults(resultes:NSDictionary)
    }
    class HttpController:NSObject{
        //定义一个可选代理
        var delegate:HttpProtocol?
         
        //定义一个方法运过来获取网络数据,接收参数为网址
         
        func onSearch(url:String){
            //定义一个NSURL
            var nsUrl:NSURL=NSURL(string: url)!
            //定义一个NSURLRequest
            var request:NSURLRequest=NSURLRequest(URL: nsUrl)
            //异步获取数据
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(),
                completionHandler: {(response:NSURLResponse!,data:NSData!,error:NSError!)->Void in
                //由于我们获取的数据是json格式,所以我们可以将其转化为字典。
                var jsonResult:NSDictionary=NSJSONSerialization.JSONObjectWithData(data,
                    options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
                //将数据传回给代理
                self.delegate?.didRecieveResults(jsonResult)
            })
        }
    }

    2,ViewController.swift (使用样例)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    import UIKit
     
    class ViewController: UIViewController,HttpProtocol {
         
        //获取网络数据的类
        var eHttp:HttpController = HttpController()
        //接收频道列表的数组
        var channelData:NSArray=NSArray()
     
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
             
            //为HttpController实例设置代理
            eHttp.delegate=self
            //获取频道数据
            eHttp.onSearch("http://www.douban.com/j/app/radio/channels")
     
        }
     
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
         
        //实现HttpProtocol协议的方法
        func didRecieveResults(results:NSDictionary){
            if (results["channels"] != nil){
                //如果channels关键字的value不为nil,获取的就是频道数据
                self.channelData=results["channels"] as NSArray
                println(self.channelData[0]["name"] as String) //私人兆赫
                 
            }
        }
    }


    3,请求数据样例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    {  
     "channels": [
            {
                "name_en": "Personal Radio",
                "seq_id": 0,
                "abbr_en": "My",
                "name": "私人兆赫",
                "channel_id": 0
            },
            {
                "name": "华语",
                "seq_id": 0,
                "abbr_en": "",
                "channel_id": "1",
                "name_en": ""
            },
            {
                "name": "欧美",
                "seq_id": 1,
                "abbr_en": "",
                "channel_id": "2",
                "name_en": ""
            }
        ]
    }
  • 相关阅读:
    黄聪:robots.txt一分钟教程
    黄聪:C#获取系统中的所有字体
    黄聪:C#下如何实现服务器+客户端的聊天程序
    黄聪:C#截取DOS命令输出流取得网卡MAC地址
    黄聪:选择适当的关键词
    黄聪:C#的Main(String[] args)参数输入问题
    黄聪:C#正则表达式整理备忘
    黄聪:【强烈推荐】搜索引擎排名决定一切吗!
    黄聪:第2章 并发操作的一致性问题 (2)
    黄聪:VS2008 "LIB 环境变量" 无效解决方案
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4841051.html
Copyright © 2020-2023  润新知