gpt4 book ai didi

ios - session.dataTaskWithURL 未按正确顺序执行

转载 作者:行者123 更新时间:2023-11-28 07:13:52 24 4
gpt4 key购买 nike

我正在调用 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: {(data, response, error) in "in a proper sequence???提前致谢。

最佳答案

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

关于ios - session.dataTaskWithURL 未按正确顺序执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27223864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com