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")
}
}
是否有實現這個代碼更安全的方式?