Reputation: 49
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
var taskString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(taskString)
if taskString == "10004" {
self.loginStatus=10004
}else if taskString == "10005" {
self.loginStatus=10005
}else if taskString == "10002" {
self.loginStatus=10002
}else if taskString == "10003" {
self.loginStatus=10003
}else if taskString == "10001" {
self.loginStatus=10001
}else{
self.loginStatus=10000
}
}
task.resume()
println(self.loginStatus)
I need to get a state through a network request I wrote the above code
task.resume()
println(self.loginStatus)
I saw it first println? println After that change 'loginStatus' content?
Upvotes: 1
Views: 3892
Reputation: 24572
NSURLSession.sharedSession().dataTaskWithRequest
is an asynchronous process that runs in a background thread. The block inside the function is called after the asynchronous process finishes downloading the data.
The execution continues after task.resume()
statement to println
while the dataTaskWithRequest
executes in the background. This is why your println
statement is executed first. To print the value after the execution of the task, put it inside the block.
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
var taskString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(taskString)
if taskString == "10004" {
self.loginStatus=10004
} else if taskString == "10005" {
self.loginStatus=10005
} else if taskString == "10002" {
self.loginStatus=10002
} else if taskString == "10003" {
self.loginStatus=10003
} else if taskString == "10001" {
self.loginStatus=10001
} else {
self.loginStatus=10000
}
println(self.loginStatus) // print it here
}
task.resume()
if loginStatus
is always an Integer, you can use toInt
function instead of the if statements.
Thus your code is simplified to
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
var taskString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(taskString)
if let status = taskString.toInt() {
self.loginStatus = status
}
else {
self.loginStatus = 10000
}
println(self.loginStatus) // print it here
}
task.resume()
Upvotes: 3