Downloading and parsing json in swift

前端 未结 9 1210
独厮守ぢ
独厮守ぢ 2020-12-02 05:37

I\'m trying to get the JSON from a website and parse it before putting it inside of an iOS view.

Here\'s my code;

func startConnection(){
        le         


        
9条回答
  •  佛祖请我去吃肉
    2020-12-02 06:24

    //
    //  ViewController.swift
    //  Test2
    //
    //  Created by fingent on 11/08/15.
    //  Copyright (c) 2015 fingent. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController,NSURLConnectionDelegate
    
    {
    lazy var data = NSMutableData()
    
        @IBAction func t1(sender: AnyObject) {
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            startConnection()
    
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        func startConnection(){
            let urlPath: String = "https://api.github.com/users/mralexgray"
            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
            println(jsonResult)
        }
    
    
    }
    

提交回复
热议问题