gpt4 book ai didi

ios - 解析 JSON 数据时无法将字符串附加到数组

转载 作者:行者123 更新时间:2023-11-29 00:53:06 25 4
gpt4 key购买 nike

我在存储从 JSON 源数据检索的结果时遇到困难。我已确认能够打印检索到的数据,但无法将其存储到我的本地数组中。

我的最终目标是在 UITableView 中实际打印结果。

下面是我的相关 TableView Controller 的代码:

import UIKit

class CommunityActivityTableViewController: UITableViewController {
var displayNameArr = [String]()
var postDateArr = [String]()
var postDetailArr = [String]()
var testArr = ["teaad"]

override func viewDidLoad() {
super.viewDidLoad()
parseJson()
print(self.displayNameArr.count) //returns 0
print(self.postDateArr.count) //returns 0
print(self.postDetailArr.count) //returns 0
print(self.testArr.count)
print("end")

}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections

return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

// #warning Incomplete implementation, return the number of rows

return self.displayNameArr.count
}



override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("3")
let cell = tableView.dequeueReusableCellWithIdentifier("Cell_activity", forIndexPath: indexPath)



print("hi")
cell.textLabel?.text = "hi"
cell.detailTextLabel?.text = "test"

return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func makeAttributedString(title title: String, subtitle: String) -> NSAttributedString {
let titleAttributes = [NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline), NSForegroundColorAttributeName: UIColor.purpleColor()]
let subtitleAttributes = [NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)]

let titleString = NSMutableAttributedString(string: "\(title)\n", attributes: titleAttributes)
let subtitleString = NSAttributedString(string: subtitle, attributes: subtitleAttributes)

titleString.appendAttributedString(subtitleString)

return titleString
}
func parseJson(){
//MARK: JSON parsing
let requestURL: NSURL = NSURL(string: "<sanitised>")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in

let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode

if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")

do{

let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

if let results = json["result"] as? [[String: AnyObject]] {

for result in results {

if let lastname = result["last_name"] as? String {

if let postdate = result["timestamp"] as? String {
if let firstname = result["first_name"] as? String {
if let postdetails = result["post_details"] as? String {

let displayname = firstname + " " + lastname
//print(displayname)
self.displayNameArr.append(displayname)
self.postDateArr.append(postdate)
self.postDetailArr.append(postdetails)
self.testArr.append("haha")


}
}

}

}
}

}

}catch {
print("Error with Json: \(error)")
}

}
}

task.resume()}


}

根据上面的代码,displaynamearr.count、postDateArr.count 和 postDetailArr.count 的打印结果在 parseJson() 方法应该返回大于 0 的结果时返回 0。

我已经打印了显示名称、游戏后和帖子详细信息变量,它们都包含数据,因此问题不在于数据的提取,而在于将数据附加到数组中。

感谢提供的任何帮助,谢谢!基于 Xcode 7 和 Swift 2.2 开发由于信息的敏感性,清理了我的 JSON 源(我已验证信息检索正常)

最佳答案

dataTaskWithRequest() 是异步数据加载。它在后台线程上加载,确保您的 UI 不会卡住。因此,当您执行此操作时,您的数组将为空,因此会出现错误。您需要像这样的完成处理程序:

   func parseJson(completion: (isDone: Bool) -> ()){

///code

for result in results {

if let lastname = result["last_name"] as? String {

if let postdate = result["timestamp"] as? String {
if let firstname = result["first_name"] as? String {
if let postdetails = result["post_details"] as? String {

let displayname = firstname + " " + lastname
//print(displayname)
self.displayNameArr.append(displayname)
self.postDateArr.append(postdate)
self.postDetailArr.append(postdetails)
self.testArr.append("haha")


}
completion(isDone: True)

}



}

现在在 viewDidLoad 中:

 override func viewDidLoad() {
super.viewDidLoad()
parseJson(){ success in
if success{
print(self.displayNameArr.count) //returns a value
print(self.postDateArr.count) //returns a value
print(self.postDetailArr.count) //returns a value
print(self.testArr.count) //This wont because I havent added it in the completion handler
print("end")
self.tableView.reloadData()
}
}
}

关于ios - 解析 JSON 数据时无法将字符串附加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37905445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com