0
从URL中填充表视图的最佳实践是从URL字符串中解析用户数据。目前代码正在工作,但如果在运行URL请求之前未加载解析用户数据,则可能会导致错误。这将导致表格无法加载(不是安全代码)使用解析和url填充UItableview
解析中的用户类有一个“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")
}
}
是否有实现这个代码更安全的方式?