如何使用闭包从NSURLSession返回JSON值

时间:2015-11-19 04:30:02

标签: ios json swift

我正在尝试从JSON对象返回结果,但无法执行此操作。我是Swift的新手,请好好解释一下如何做到这一点。在下面的代码中,我想在函数json_level_number的返回中返回fetchNumberOfSections (),其中我现在硬编码为5 return 5。如果我在可达性代码之上声明一个变量json_level_number,它可以解决问题,但是它第一次返回'0'。 API每次返回2.

代码如下:

func fetchNumberOfSections () -> Int {
    if Reachability.isConnectedToNetwork() == true {
        // Below code to fetch number of sections 
        var urlAsString = "http://themostplayed.com/rest/fetch_challenge_sections.php"
        urlAsString = urlAsString+"?apiKey="+apiKey
        print (urlAsString)
        let url = NSURL(string: urlAsString)!
        let urlSession = NSURLSession.sharedSession()
        let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
            if (error != nil) {
                print(error!.localizedDescription)
            }
            do {
                let jsonResult = (try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
                let json_level_number: String! = jsonResult["level_number"] as! String
                //
                dispatch_async(dispatch_get_main_queue(), {
                    //                self.dateLabel.text = jsonDate
                    //                self.timeLabel.text = jsonTime
                    print(json_level_number)  
               //     self.activityIndicatorStop()
                })
            }
            catch let errorJSON {
                print (errorJSON)
                // alert box code below
                let alert = UIAlertController(title: "JSON Error!", message:"Error processing JSON.", preferredStyle: .Alert)
                let action = UIAlertAction(title: "OK", style: .Default) { _ in
                    // Put here any code that you would like to execute when
                    self.dismissViewControllerAnimated(true, completion: {})
                }
                alert.addAction(action)
                self.presentViewController(alert, animated: true, completion: nil)
                // alert box code end
            }
        })
        jsonQuery.resume()
        // End
    }
    else {
        print("Internet connection FAILED")
        self.performSegueWithIdentifier("nointernet", sender: nil)
    }
    return 5
}

0 个答案:

没有答案