Swift-网络、本地数据解析

前端之家收集整理的这篇文章主要介绍了Swift-网络、本地数据解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

数据地址

let _urlPath = NSBundle.mainBundle().pathForResource("news_list.json",ofType: nil)

1.对对象进行解析

//解析对象
    func jsonUser(){

        //Swift对象
        let user = [
            "user": "张三","name": ["name1": "大名","name2": "小名"]
        ]
        //首先判断能不能转换
        if (!NSJSONSerialization.isValidJSONObject(user)) {
            print("is not a valid json object")
            return
        }
        //将对象转换为NSData
        let data : NSData! = try? NSJSONSerialization.dataWithJSONObject(user,options: [])

        //把NSData对象转换回JSON对象
        let json : AnyObject! = try? NSJSONSerialization
            .JSONObjectWithData(data,options:NSJSONReadingOptions.AllowFragments)

        //验证JSON对象可用性
        let users : AnyObject = json.objectForKey("user")!
        let name1 : AnyObject = json.objectForKey("name")!.objectForKey("name1")!
        let name2 : AnyObject = json.objectForKey("name")!.objectForKey("name2")!
        print("users: \(users),name1: \(name1),name2 :\(name2)")

    }

2、对本地json进行解析

func localData(){
        let recvData2 = NSData.dataWithContentsOfMappedFile(_urlPath!) as! NSData
        let tempArray  = try? NSJSONSerialization.JSONObjectWithData(recvData2,options: .MutableContainers)
        //json解析然后强转
        if (tempArray?.count > 0){
            for (var i = 0; i < tempArray?.count; i++){
                let oneVideo = tempArray?[i] as! NSDictionary
                //把里面转成字典
                let id = oneVideo.objectForKey("id")
                let type = oneVideo.objectForKey("type")
                let title = oneVideo.objectForKey("title")
                let summary = oneVideo.objectForKey("summary")
                let image = oneVideo.objectForKey("image")

                let model = ZWModel()
                model.id  = id as! Int
                model.type = type as! Int
                model.title = title as? String
                model.summary = summary as? String
                model.image = image as? String

                //把数据添加到模型数据
                dataArray.addObject(model)
            }
            _tableView?.reloadData()
        }
    }

3、使用NSURLConnection

func downloadData(){
       //创建NSURL
        //请求本地数据
        let url = NSURL(fileURLWithPath: _urlPath!)
        //请求网络数据
         //let url = NSURL(string: _urlPath!)
        //以url创建请求
        let request = NSURLRequest(URL:url!)

        //创建连接
        _connection = NSURLConnection (request: request,delegate: self)

    }

//收到http相应头
    func connection(connection: NSURLConnection,didReceiveResponse response: NSURLResponse){

    }
    //接收一段数据,这个函数会被调用多次
    func connection(connection: NSURLConnection,didReceiveData data: NSData){
       //把接收到的数据追加到_recvData后面
        _recvData.appendData(data)
    }


    //数据接收完成
    func connectionDidFinishLoading(connection: NSURLConnection){
        //接收完成函数显示要解析的json
        let str = NSString(data: _recvData,encoding: NSUTF8StringEncoding)
        //把二进制转化成字符串
        print("s is \(str)")
        //
        let videoArr = try? NSJSONSerialization.JSONObjectWithData(_recvData,options:.MutableContainers)
        //json解析然后强转
        if (videoArr?.count > 0){
            for (var i = 0; i < videoArr?.count; i++){
              let oneVideo = videoArr?[i] as! NSDictionary
                //把里面转成字典
                let id = oneVideo.objectForKey("id")
                let type = oneVideo.objectForKey("type")
                let title = oneVideo.objectForKey("title")
                let summary = oneVideo.objectForKey("summary")
                let image = oneVideo.objectForKey("image")

                let model = ZWModel()
                model.id  = id as! Int
                model.type = type as! Int
                model.title = title as? String
                model.summary = summary as? String
                model.image = image as? String

                //把数据添加到模型数据
                dataArray.addObject(model)
            }
        }

        //重新刷新表格
        _tableView?.reloadData()
    }

4、网络数据的请求和解析将(3)中的//请求网络数据 //let url = NSURL(string: _urlPath!)放开,地址改为网络地址

原文链接:https://www.f2er.com/swift/324320.html

猜你在找的Swift相关文章