session.dataTaskWithURL未按正确顺序执行

时间:2014-12-01 07:50:01

标签: ios swift nsurlsessiondatatask

我正在调用Web服务。 在那个方法中,session.dataTaskWithURL在一段时间后调用。我认为它没有给出正确的线程吗?

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;
}

如果我们可以执行我的方法" session.dataTaskWithURL(url!,请帮助我) completionHandler:{(数据,响应,错误)在"以适当的顺序??? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

    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()