我编写了RetrieveUrl类来从URL获取JSON数据。这一切都按预期工作,我可以看到一个闭包中的数据变量返回一个值。但我想在MasterViewController.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
}
答案 0 :(得分:1)
更新的代码: class RetrieveUrl {
func httpGet(request: NSURLRequest!, callback: (NSString, NSString?) -> 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(callback: (NSString) ->Void) -> Void {
var request = NSMutableURLRequest(URL: NSURL(string: "http://sample_url")!)
var result:NSString = ""
httpGet(request){
(data, error) -> Void in
if error != nil {
result = error!
} else {
result = data
}
callback(data)
}
}
}
用法:
let retrieveObj = RetrieveUrl()
retrieveObj.makeRequest(){
(data) -> Void in
println("response data:\(data)")
}
}