我正在研究一个应用程序,该应用程序从数据库中检索用户的朋友,然后在表格视图中输出。运行良好的代码在viewDidLoad()中使用时崩溃应用程序
我已成功将表视图编码为读取我插入到NSMutableArray()中的索引的位置。我的想法是使用NSURL通过使用PHP的URL变量向MySQL数据库发送查询。我使用NSURL多次与数据库进行交互,但是当我在viewDidLoad()函数中使用它来立即在应用程序加载时加载好友时,它崩溃但不返回错误。
代码:
class viewFriendsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var textArray: NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
let myUrl = NSURL(string: "http://www.casacorazon.org/ios.html")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
if error != nil {
print("Error: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
print(responseString)
}
}
}
task.resume()
//get username from NSUserDefaults
//if username inavailable, insert error report into first row
//use PHP script to get friends from user's database
//split return string by '9245203598' into array
//load split array into NSMutableArray via foreach loop
//let username = NSUserDefaults.standardUserDefaults().stringForKey("username")*/
self.textArray.addObject("First Index")
self.textArray.addObject("Second Index")
self.textArray.addObject("Third Index")
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.textArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel?.text = self.textArray.objectAtIndex(indexPath.row) as? String
return cell
}
func sendAlert(subject: String, message: String) {
let alertController = UIAlertController(title: subject, message:
message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
你有没有尝试将代码移到viewWillAppear? – RichAppz
你应该使用一些错误处理。 – lukaivicev
你调试了吗?设置断点并查看哪些值为零。 – lukaivicev