ios - How to switch views in the handler of an NSURLSession Request -


i have login view controller, , other view controller. i'd is: when user hits login, sends credentials remote server. remote server returns response indicating whether credentials or not, , if good, app redirects other view controller.

the code below crashes @ call .performseguewithidentifier.

the crash gives error code of exc_bad_access(code=1, address=0xbbadbeef)

question: swifty way of doing this?

var request = nsmutableurlrequest(url: nsurl(string: "http://url.to/my/login/handler")!) var session = nsurlsession.sharedsession() request.httpmethod = "post"  //user initialized earlier bodydata = "email=\(user.username)&password=\(user.password)"  request.httpbody = bodydata.datausingencoding(nsutf8stringencoding);  var task = session.datataskwithrequest(request, completionhandler: {data, response, error -> void in     // check log in successful looking in 'response' arg     // if login successful     self.performseguewithidentifier("seguetoothercontroller", sender: self)     } task.resume() } 

if it's crashing, should share details crash in order identify why. problems include didn't find segue of identifier "storyboard id" current view controller next scene. it's impossible without details on precise error.

having said that, there problem here: completion block may not run on main thread, ui updates must happen on main thread. make sure dispatch main queue, e.g.

let request = nsmutableurlrequest(url: nsurl(string: "http://url.to/my/login/handler")!) let session = nsurlsession.sharedsession() request.httpmethod = "post"  //user initialized earlier bodydata = "email=\(user.username)&password=\(user.password)"  request.httpbody = bodydata.datausingencoding(nsutf8stringencoding);  let task = session.datataskwithrequest(request) {data, response, error in     // check log in successful looking in 'response' arg     // if login successful     dispatch_async(dispatch_get_main_queue()) {         self.performseguewithidentifier("seguetoothercontroller", sender: self)     } } task.resume() 

note, changed of var references let (as general rule, use let wherever possible). also, haven't tackled here, should percent escaping username , password properties. if, example, password included reserved characters + or &, fail. there lots of ways of doing that, e.g. method discussed here: https://stackoverflow.com/a/26317562/1271826 or https://stackoverflow.com/a/25154803/1271826.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -