Downloading and parsing json in swift

前端 未结 9 1168
独厮守ぢ
独厮守ぢ 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:20

    The example below sends a request to fetch stock information - it's a bit more comprehensive, but has more cleanup and structure:

    import Foundation
    
    private let kSNStockInfoFetchRequestPath:String = "http://dev.markitondemand.com/Api/v2/Quote/json"
    
    private func SNStockInfoFetchRequestURL(symbol:String) -> NSURL? {
      if let components:NSURLComponents = NSURLComponents(string:kSNStockInfoFetchRequestPath) {
        components.queryItems = [NSURLQueryItem(name:"symbol", value:symbol)]
        return components.URL
      }
      return nil
    }
    
    private func SNStockInfoFetchRequestURLRequest(symbol:String) ->  NSURLRequest? {
      if let requestURL:NSURL = SNStockInfoFetchRequestURL(symbol) {
        var request:NSMutableURLRequest = NSMutableURLRequest(URL:requestURL)
        request.HTTPMethod = "GET"
        return request
      }
      return nil
    }
    
    private func SNStockInfoFetchRequestParseData(receivedData:NSData, error:NSErrorPointer) -> NSDictionary? {
      return NSJSONSerialization.JSONObjectWithData(receivedData, options:NSJSONReadingOptions.MutableContainers, error:error) as? NSDictionary
    }
    
    class SNStockInfoFetchRequest: NSObject,
    NSURLConnectionDataDelegate
    {
      private let symbol:String
      private (set) var fetching:Bool
      private lazy var receivedData = NSMutableData()
    
      init(symbol:String) {
        self.symbol = symbol
        self.fetching = false
      }
    
      func start() {
        assert(!fetching, "Should not start a request that has already started!")
        fetching = true
        if let request:NSURLRequest = SNStockInfoFetchRequestURLRequest(symbol) {
          var connection:NSURLConnection = NSURLConnection(request:request, delegate:self, startImmediately:true)!
          connection.start()
        }
      }
    
      // MARK: NSURLConnectionDataDelegate
    
      func connection(connection:NSURLConnection, didReceiveData data:NSData) {
        assert(fetching, "Should only receive data while activly fetching!")
        self.receivedData.appendData(data)
      }
    
      func connectionDidFinishLoading(connection:NSURLConnection) {
        var error:NSError?
        if let result:NSDictionary = SNStockInfoFetchRequestParseData(receivedData, &error) {
          println(result)
        } else {
          println(error)
        }
    
      }
    }
    

    We can now use the request as such:

    let fetcher:SNStockInfoFetchRequest = SNStockInfoFetchRequest(symbol:"MSFT")
    fetcher.start()
    

    This should output the JSON in case of a success, or the error in case of a failure. Hope this helps! If you use the same structure, make sure to use a delegate to either return the parsed JSON (or even better, an immutable value object) or indicate a failure.

    0 讨论(0)
  • 2020-12-02 06:23

    These two functions worked for me:

        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, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
    
            return boardsDictionary
        }
    
    0 讨论(0)
  • 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)
        }
    
    
    }
    
    0 讨论(0)
提交回复
热议问题