Downloading JSON with NSURLSession doesn't return any data

前端 未结 1 1891
长发绾君心
长发绾君心 2020-11-28 16:33

I am currently trying to download, parse and print JSON from an URL. So far I got to this point:

1) A class (JSONImport.swift), which handles my import:



        
相关标签:
1条回答
  • 2020-11-28 17:02

    Here's an example on how to use NSURLSession with a very convenient "completion handler".

    This function contains the network call and has the "completion handler" (a callback for when the data will be available):

    func getDataFrom(urlString: String, completion: (data: NSData)->()) {
        if let url = NSURL(string: urlString) {
            let session = NSURLSession.sharedSession()
            let task = session.dataTaskWithURL(url) { (data, response, error) in
                // print(response)
                if let data = data {
                    completion(data: data)
                } else {
                    print(error?.localizedDescription)
                }
            }
            task.resume()
        } else {
            // URL is invalid
        }
    }
    

    You can use it like this, inside a new function, with a "trailing closure":

    func apiManager() {
        getDataFrom("http://headers.jsontest.com") { (data) in
            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
                if let jsonDict = json as? NSDictionary {
                    print(jsonDict)
                } else {
                    // JSON data wasn't a dictionary
                }
            }
            catch let error as NSError {
                print("API error: \(error.debugDescription)")
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题