在swift中下载和解析json

前端之家收集整理的这篇文章主要介绍了在swift中下载和解析json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从一个网站获取JSON并解析它,然后将其放入iOS视图。

这里是我的代码;

func startConnection(){
        let urlPath: String = "http://binaenaleyh.net/dusor/"
        var url: NSURL = NSURL(string: urlPath)
        var request: NSURLRequest = NSURLRequest(URL: url)
        var connection: NSURLConnection = NSURLConnection(request: request,delegate: self,startImmediately: false)
        connection.start()
    }

    func connection(connection: NSURLConnection!,didReceiveData data: NSData!){
        self.data.appendData(data)
    }

    func buttonAction(sender: UIButton!){
        startConnection()
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        var err: NSError
        // throwing an error on the line below (can't figure out where the error message is)
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data,options: NSJSONReadingOptions.MutableContainers,error: nil) as NSDictionary
    }

这是JSON的链接;

http://binaenaleyh.net/dusor/

我在这里做错了什么?

这两个函数为我工作:
func getJSON(urlToRequest: String) -> NSData{
        return NSData(contentsOfURL: NSURL(string: urlToRequest))
    }

    func parseJSON(inputData: NSData) -> NSDictionary{
        var error: NSError?
        var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData,error: &error) as NSDictionary

        return boardsDictionary
    }
原文链接:https://www.f2er.com/swift/321079.html

猜你在找的Swift相关文章