简体   繁体   English

swift 2如何在函数外使用变量?

[英]swift 2 how to use variable outside the function?

I have a class ApiManager() that make request to JSON data in which I learned from this tutorial , which used protocol delegate approach to pass the data to ViewController class 我从本教程中学到了一个类ApiManager()来请求JSON数据,该类使用协议委托方法将数据传递给ViewController类。

The data is acquired fine but I am not sure how to use it around?! 数据可以很好地获取,但我不确定如何使用它! in this case I am trying to use it inside TableView 在这种情况下,我试图在TableView中使用它

class ViewController: UITableViewController, ApiManagerDelegate{

var names:[String] = []  // the variable which will hold the JSON data

override func viewDidLoad() {
    super.viewDidLoad()

    //instantiate the ApiManager Class
    //Set the ViewController as its delegate
    //perform request to Restaurants info

    let manager = ApiManager()
    manager.delegate = self
    manager.getRestaurantsData()

    func didReceiveResponse (info: [String : AnyObject]){

        //Read name property from data dictionary (JSON)

        if let restaurantsData = info["restaurants"] as? [[String: AnyObject]]{

            for restaurant in restaurantsData{
                let name = restaurant["name"] as? String
                self.names.append(name!)
            }
        }


        print("Data1: \(names)") // prints the data perfectly

    }

    func didFailToReceiveResponse() {
        print("There was an error in recieving API data")
    }

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print (names) //no data here
    return names.count //not working
}

I am a bit confused how to work around this, I tried to make return value to didReieveResponse(), but the issue is when I call the function it needs the argument (which is passed to it in the Delegator class "dictionary").. I am completely confused. 我有点困惑如何解决此问题,我试图为didReieveResponse()返回值,但是问题是当我调用该函数时需要参数(在Delegator类“ dictionary”类中传递给它)。我完全感到困惑。

Here is the delegator class and protocol for reference: 这是供参考的委托类和协议:

import UIKit

//Custom Protocol Declaration
@objc protocol ApiManagerDelegate {
    optional func didReceiveResponse(info: [ String : AnyObject ])
    optional func didFailToReceiveResponse()
}


class ApiManager: NSObject, NSURLSessionDelegate {

//open restaurant web API
private let requestURL = NSURL(string:"http://some-url-here.com")

var delegate: ApiManagerDelegate?

override init() {

    super.init()

}

func getRestaurantsData() {

    let defaultConfigObject = NSURLSessionConfiguration.defaultSessionConfiguration()

    let defaultSession = NSURLSession (configuration: defaultConfigObject, delegate: self, delegateQueue: NSOperationQueue.mainQueue ())

    let request = NSMutableURLRequest(URL: requestURL!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 60 )



    request.HTTPMethod = "POST"
    request.setValue( "application/x-www-form-urlencoded" , forHTTPHeaderField: "Content-Type" )

    let dataTask = defaultSession.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) in

            if let responseError = error {

                self.delegate?.didFailToReceiveResponse?()
                print("Reponse Error: \( responseError )" )

                } else {
                    do {
                        let dictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String: AnyObject]

                        self.delegate?.didReceiveResponse?(dictionary)
                        //print( "Response: \( dictionary )" )
                        print("Response: Success")

                    } catch let jsonError as NSError {
                        // Handle parsing error
                        self.delegate?.didFailToReceiveResponse?()
                        print( "JSONError: \(jsonError.localizedDescription)")
                    }
                }
            })

            dataTask.resume()
}

} }

thanks, 谢谢,


Update: 更新:

For future Developers who might suffer like me, the solution is to use TableViewName.reloadData() as mentioned below.. But please notice, it did only worked with me when I placed DidRecieveResponse() function outside ViewDidLoad, not sure why Hopefully one of the experts can explain it later. 对于将来可能像我一样遭受痛苦的开发人员,解决方案是使用TableViewName.reloadData(),如下所述。。但是请注意,仅当我将DidRecieveResponse()函数放在ViewDidLoad之外时,它才与我一起工作,不知道为什么希望其中之一专家可以稍后解释。

Enjoy! 请享用!

do like 喜欢

 class ViewController: UITableViewController, ApiManagerDelegate{

var names:[String] = []  
 let manager = ApiManager()


 override func viewDidLoad() {
    super.viewDidLoad()

    manager.delegate = self
    manager.getRestaurantsData()
 }

   func didReceiveResponse (info: [String : AnyObject]){

        //Read name property from data dictionary (JSON)

        if let restaurantsData = info["restaurants"] as? [[String: AnyObject]]{

            for restaurant in restaurantsData{
                let name = restaurant["name"] as? String
                self.names.append(name!)
            }

                print("Data1: \(names)") // prints the data perfectly
             if (self.names.count>0)
             { 
              yourtableview.reloadData()
             }
        }

    }


  func didFailToReceiveResponse() {
    print("There was an error in recieving API data")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM