ios


How to move code execution to the main qeue


I'd like to mention that I've seen a lot of similar questions and tried code from there, but still my code runs asynchronously (I move to another ViewController only after second click on LogIn Button. That's why I would really appreciate you pointing out the problem in my code rather then referencing me to someone's else.
I have a method which sends logIn data to server
import UIKit
var IS_LOGGED_IN = Bool()
class LoginDataSender: UIView {
func sendLogInData() {
let myUrl = NSURL(string: "https://somewebsite")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = "username=NAME&password=PASS"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, respoonse, error) in
if error != nil
{
print("error=\(error)")
return
}
dispatch_async(dispatch_get_main_queue(), {
do {
let myJson = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
IS_LOGGED_IN = myJson.valueForKey("status") as! Bool
print(IS_LOGGED_IN)
} catch {
print(error)
}
})
}.resume()
}
}
and I call this method from a ViewController
import UIKit
class LoginViewController: UIViewController {
let logInDataSender = LoginDataSender()
#IBAction func pressLoginButton(sender: AnyObject) {
logInDataSender.sendLogInData()
if IS_LOGGED_IN {
performSegueWithIdentifier("LogInSegue", sender: self)
}
}
As you see I store result result in a global variable IS_LOGGED_IN and based on that I whether perform segue or not.
For now I just hardcode login/password for testing purposes.
Where should I place dispatch_async to be able to use IS_LOGGED_IN value when clicking LogIn button for the first time? Thanks a lot!
Instead of your global variable, make a practice to use completion handlers. In this your case, you may use like:
func sendLogInData(completionhandler: (Bool)->()) {
//.......
dispatch_async(dispatch_get_main_queue(), {
do {
let myJson = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
completionhandler(myJson.valueForKey("status") as! Bool)
} catch {
completionhandler(false)
print(error)
}
})
//.....
}
And then in your action method of LoginViewController:
#IBAction func pressLoginButton(sender: AnyObject) {
logInDataSender.sendLogInData { (loggedIn) in
if loggedIn == true {
//Logged In
performSegueWithIdentifier("LogInSegue", sender: self)
}else{
//Not logged in
}
}
}

Related Links

Master-detail segue from DetailViewController with back button
Change date format using NSDateFormatter
How passing data with multiple prepareforsegue in a uitableviewcell swift
UITextViewDelegate in non viewcontroller class
How can I get indexPath of a uiview on a cell - iOS
How to allow audio to continue to play when app is backgrounded?
How to limit the pulling distance with a refresh control?
Image fits into UICollectionView Cell
Caching the downloaded data
Core Location and Google Maps
(Objective C) NSDate is nil to convert a date in String
Swift need to reload TableView that is contained within a containerView
Remove iAds from SKScene
Adjust UICollectionView Size Dynamically to Ensure No Inter Item Spacing
How to replace Detail in UISplitViewController in Swift?
Adding Delay In A For Loop Without Blocking UI

Categories

HOME
jsp
openshift-origin
android-sqlite
compiler-errors
react-navigation
parse.com
datetime
encog
gluon
wget
dbus
obiee
reload
numericupdown
condor
watchservice
jmespath
flow
orientdb-2.1
mediator
pvs-studio
structure
fat-free-framework
meanjs
coqide
jtapi
imageshack
seh
decompiler
rights-management
runge-kutta
knowledge-management
atlassian-bitbucketserver
brainfuck
php-5.5
httpexception
botkit
hostapd
wrk
xbrl
abbyy
glumpy
assembly-references
jeditorpane
callkit
postmark
mink
redux-framework
xceed
xpdf
ellipsis
kernighan-and-ritchie
illegalstateexception
filenet-content-engine
genetic
domo
uat
nominatim
quasar
crosswalk
gulp-rename
selectsinglenode
access-log
omap
movie
window-server
javaw
java-client
slick2d
cvs2git
computer-science-theory
sqlhelper
bessel-functions
short
dirpagination
delphi-2009
jxta
nmea
hla
adlds
chromeless
speaker
html5-apps
hamlc
oncreate
cocosbuilder
lungojs
freeglut
android-actionmode
arr
ria
quilt
ms-access-97
postgresql-8.1
combinators
eye-detection
network-scan
markitup
code-statistics

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App