我试图从一个网站获取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/
我在这里做错了什么?
这两个函数为我工作:
原文链接:https://www.f2er.com/swift/321079.htmlfunc 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 }