[英]swift 2 how to use variable outside the function?
我從本教程中學到了一個類ApiManager()來請求JSON數據,該類使用協議委托方法將數據傳遞給ViewController類。
數據可以很好地獲取,但我不確定如何使用它! 在這種情況下,我試圖在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
}
我有點困惑如何解決此問題,我試圖為didReieveResponse()返回值,但是問題是當我調用該函數時需要參數(在Delegator類“ dictionary”類中傳遞給它)。我完全感到困惑。
這是供參考的委托類和協議:
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()
}
}
謝謝,
對於將來可能像我一樣遭受痛苦的開發人員,解決方案是使用TableViewName.reloadData(),如下所述。。但是請注意,僅當我將DidRecieveResponse()函數放在ViewDidLoad之外時,它才與我一起工作,不知道為什么希望其中之一專家可以稍后解釋。
請享用!
喜歡
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.