David David - 1 year ago 74
iOS Question

UI freezes and action get executed with a delay

I'm developing an iOS app with Xcode and Swift.

I have a problem with this code:

@IBAction func login(sender: AnyObject) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://myurl.com/contact/checklogin.php")!)
request.HTTPMethod = "POST"
let postString = "username=\(username.text!)&password=\(password.text!)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")

if (responseString == "false") {
let alert = UIAlertView(title: "Error!", message: "Something is wrong. Please check this!", delegate: nil, cancelButtonTitle: "Okay")
else {
let alert = UIAlertView(title: "Successful!", message: "You'll get logged in now!", delegate: nil, cancelButtonTitle: "Okay")

When user logs in this code sends username and password to a PHP scipt on my server. This PHP script checks if this data/password pair really exist. If so it responses "true", else "false".

The problem is:
When user taps submit, (this code will run), the UI freezes for some seconds and the alert needs ca. 15 seconds to appear. But it's not a PHP script mistake, because
print("responseString = \(responseString)")
prints immediately. I'm also getting this error message: https://codeshare.io/TGwe6

Does anybody know what I'm doing wrong?


I know that many thinks are missing in the code (like hash instead of password or check for empty files). This is just an example.

P.P.S: Updated the code. It's working now.

Answer Source

You need to show alert on main thread, always perform UI changes on main thread like this.

     //Show alert

Note: You need to use UIAlertController instead of UIAlertView because it is deprecated.

There are many tutorial for AlertController, some of these are as below.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download