我寫了RetrieveUrl類來從URL獲取JSON數據。這一切都按預期工作,我可以看到閉包中的數據變量返回了一個值。但我想在MasterViewController.swift的表格中顯示這些數據,但嘗試了幾件事情,但似乎我對Swift閉包知之甚少。如何在Swift中從閉包中獲取數據
import Foundation
class RetrieveUrl {
func httpGet(request: NSURLRequest!, callback: (String, String?) -> Void)
{
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if error != nil {
callback("", error.localizedDescription)
} else {
var result = NSString(data: data, encoding:
NSASCIIStringEncoding)!
callback(result, nil)
}
}
task.resume()
}
func makeRequest() ->() {
var request = NSMutableURLRequest(URL: NSURL(string: "http://someapi_url")!)
var result:String = ""
httpGet(request){
(data, error) -> Void in
if error != nil {
result = error!
} else {
result = data
}
}
}
}
MasterViewController.swift代碼,我想將此數據
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let object = objects[indexPath.row] as NSDate
// Showing data from URL
var getUrlObject = RetrieveUrl()
getUrlObject.makeRequest()
cell.textLabel!.text = object.description
return cell
}
你爲什麼要從cellForRowAtIndexPath()方法發出請求?我希望你知道dataTaskWithRequest()會爲你提供異步的數據。 – Abdullah 2015-03-31 11:47:31
這是我的第一個iOs應用程序,我只想先從網址獲取數據,然後在手機屏幕上的某處顯示它,所以我對此不太瞭解,所以如果您能向我展示最佳做法,它將會非常感激。 – 2015-03-31 13:14:30