我正在开发一个应用程序,它从数据库中检索用户的朋友,然后在表格视图中输出。
我已成功将表视图编码到读取我插入NSMutableArray()的索引的位置。我的想法是使用NSURL通过PHP变量通过URL变量向MySQL数据库发送查询。
我多次使用NSURL与数据库进行交互,但是当我在viewDidLoad()函数中使用它来立即在应用程序的加载中加载朋友时,它会崩溃但不会返回错误。< / p>
代码:
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)
}
}
答案 0 :(得分:2)
因为您的应用在后台完成任务之前完成了用户界面中的代码排除。您必须确保后台任务已完成,然后在UI中继续。
注意:NSUrlsesstion在后台运行,您不必在其中导入dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0)){}。