【发布时间】:2016-01-20 23:35:56
【问题描述】:
什么是从 URL 填充 tableview 的最佳实践,该 URL 从 URL 字符串中解析用户数据。当前代码正在运行,但如果在运行 URL 请求之前未加载解析用户数据,则可能会导致错误。这将导致表格无法加载(不是安全代码)
解析中的用户类有一个“teamNumber”键,它插入到 URL 中以获取页面源的字符串。从那里处理字符串以创建一个显示为表格视图的数组。
这里是代码(编辑去掉字符串操作):
override func viewDidLoad() {
super.viewDidLoad()
//To the internet to grab the "leagueNumber" of a user to input into the attemptedUrl string
let leagueNumber = PFUser.currentUser()!["leagueNumber"] as? String
//Plug in the league number from parse into URL string
let attemptedUrl = NSURL(string: "http://someURL.leagueapps.com/leagues/\(leagueNumber!)/teams")
if let url = attemptedUrl {
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
if let urlContent = data {
let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)
//Manipulate string to get the team information
//Ends up with array [team1, team2, team3, team4] to populate the tableview
}
} else {
print("URL could not connect")
}
//Close internet session
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}
task.resume()
} else {
print("Fail")
}
}
有没有更安全的方法来实现这段代码?
【问题讨论】:
标签: ios xcode swift uitableview parse-platform