session.dataTaskWithURL is not executing in proper sequence

666 views Asked by At

I am calling Web service. In that method session.dataTaskWithURL is calling after some time.I think it is not giving in proper thread?

my code below
——--------------

 func callService(usr: String, pwdCode: String) ->Bool
{
var resultPage=false
let url = NSURL(string: "demourl")
var xmlParse:NSString = ""
var data : NSData!

println("Before request *****************")

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)

session.dataTaskWithURL(url!,
completionHandler: {(data, response, error) in

let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
let dictionary = ["email": usr, "userPwd": pwdCode] as NSDictionary
var error: NSError?

if let body = NSJSONSerialization.dataWithJSONObject(dictionary, options: nil, error: &error) {
request.HTTPBody = body
} 
else
{
    println("JSON error: \(error)")
}

let xmlParse=NSString(data: data, encoding: NSUTF8StringEncoding)!

if data == nil {
    println("dataTaskWithRequest error: \(error)")
return
}

let parser = NSXMLParser(data: data)
parser.delegate = self
resultPage=parser.parse()

println("******** boolVal \(resultPage)")
}).resume()

println("After request *****************")
println("resultPage Final \(resultPage)")
return resultPage;
}

Can you please help me if we can execute my method "session.dataTaskWithURL(url!, completionHandler: {(data, response, error) in " in a proper sequence??? Thanks in advance.

1

There are 1 answers

0
dhaval shah On BEST ANSWER
    var resultPage=false
    let url = NSURL(string: "URL")
    var xmlParse:NSString  = ""
    var data : NSData!

    let request = NSMutableURLRequest(URL: url!)
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.HTTPMethod = "POST"
    let dictionary = ["email": base64String, "userPwd": base64StringPwd] as NSDictionary
    var error: NSError?
    if let body = NSJSONSerialization.dataWithJSONObject(dictionary, options: nil, error: &error)        {
        request.HTTPBody = body
    } else {
        println("JSON error: \(error)")
    }

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    (data, response, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
    let xmlParse=NSString(data: data, encoding: NSUTF8StringEncoding)!

    if data == nil {
    println("dataTaskWithRequest error: \(error)")
    return
    }

    let parser = NSXMLParser(data: data)


    println("parser \(parser)")
    parser.delegate = self
    resultPage=parser.parse()


    if self.success==false
    {

        println("success \(self.success)")
        self.lblMessage.hidden=false
    }

}
    task.resume()