我有一个函数可以从JSON字符串中返回已解析的信息。
var info = [AppModel]()
func getEarthquakeInfo(completion: (results : NSArray?) ->Void ){
DataManager.getEarthquakeDataFromFileWithSuccess {
(data) -> Void in
let json = JSON(data: data)
if let JsonArray = json.array {
for appDict in JsonArray {
var ids: String? = appDict["id"].stringValue
var title: String? = appDict["title"].stringValue
var time: String? = appDict["time"].stringValue
var information = AppModel(idEarth: ids, title: title, time: time)
self.info.append(information)
completion(results: self.info)
}
}
}
}
此函数使用SwiftyJSON并使用我的DataManager类调用Web服务。当我在函数外打印出来时,我得到了我需要的所有信息。现在我想使用标题信息来填充我的TableView。在我的cellForRowAtIndexPath中,我尝试过滤掉我的地球信息,这样我就可以得到标题并将其放入数组中,并用该数组填充我的tableView。到目前为止,我一直没有成功,而且我一直在寻找如何做到这一点以及我尝试或发现的任何工作。有人能指出我如何做到这一点的正确方向? 到目前为止我做了什么:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
getEarthquakeInfo( { (info) -> Void in
var Earthinformation = self.info as NSArray
let titleArray = Earthinformation["TITLE"] as NSArray // error: type int does not conform to protocol "StringLiteralConvertible"
cell.textLabel!.text = titleArray[indexPath.row]
})
return cell
}
我打印出地球信息后得到的3条记录:ID:146323,TITLE:M 1.6 - 27km E of Coso Junction,California,时间:2015-04-15 14:08:20 UTC, ,ID:146346,标题:M 1.8 - 26公里E的Coso Junction,加利福尼亚,时间:2015-04-15 14:08:20 UTC, ,ID:146324,标题:M 2.4 - 26 km NW of Anchor Point,Alaska,时间:2015-04-15 13:33:36 UTC,
编辑: 对不起,我之前应该包括这个: 我的AppModel.swift:
class AppModel: NSObject, Printable {
let idEarth: String
let title: String
let time: String
override var description: String {
return "ID: \(idEarth), TITLE: \(title), TIME: \(time), \n"
}
init(idEarth: String?, title: String?, time: String?) {
self.idEarth = idEarth ?? ""
self.title = title ?? ""
self.time = time ?? ""
}
}
我的DataManager.swift文件:
let earthquakeURL = "http://www.kuakes.com/json/"
class DataManager {
class func getEarthquakeDataFromFileWithSuccess(success: ((websiteData: NSData) -> Void)) {
//1
loadDataFromURL(NSURL(string: earthquakeURL)!, completion:{(data, error) -> Void in
//2
if let urlData = data {
//3
success(websiteData: urlData)
}
})
}
class func loadDataFromURL(url: NSURL, completion:(data: NSData?, error: NSError?) -> Void) {
var session = NSURLSession.sharedSession()
// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if let responseError = error {
completion(data: nil, error: responseError)
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
var statusError = NSError(domain:"com.kuakes", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(data: nil, error: statusError)
} else {
completion(data: data, error: nil)
}
}
})
loadDataTask.resume()
}
}
答案 0 :(得分:1)
每次创建单元格时,您都在调用getEarthquakeInfo
函数。这是非常不必要的,可能会导致无意识的行为(因为getEarthquakeInfo
函数是异步的)。我建议您使用已有的模型数组信息来填充您的tableview。在viewDidLoad中调用异步函数来检索模型数组的数据。例如:
override func viewDidLoad() {
super.viewDidLoad()
getEarthquakeInfo { (info) in
// Your model array is now populated so we should reload our data
self.tableView.reloadData()
}
}
现在,调整UITableViewDataSource
函数以正确处理模型数组。请注意,我假设您的info
数组是填充tableView的UITableViewController
的属性。例如:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier",
forIndexPath: indexPath) as UITableViewCell
// Note that I have no idea how you access the title of your AppModel
// object so you may have to adjust the below code
cell.textLabel!.text = self.info[indexPath.row].title
return cell
}
override func numberOfSectionsInTableView() {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) {
return info.count
}