我正在调用Web服务并获取令牌。我尝试了不同的方法来保护全局变量,现在尝试了一个单例。当我在设置之后立即打印该值时,我得到了值,但是一旦我退出Web服务request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data ,response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = (response)")
}
// Get rid of ekstra escape chars
let responseString = String(data: data, encoding: .utf8)
let newString = responseString?.replacingOccurrences(of: "\\", with: "")
let newString2 = newString?.replacingOccurrences(of: "\"{", with: "{")
let newString3 = newString2?.replacingOccurrences(of: "}\"", with: "}")
let newdata = newString3?.data(using: .utf8)!
do {
let json = try JSONSerialization.jsonObject(with: newdata!, options: .allowFragments) as! [String:Any]
Singleton.sharedInstance.setToken(Token: (json["SessionToken"] as? String)! )
print(Singleton.sharedInstance.getToken()) // VALUE CORRECT
} catch let error as NSError {
print(error)
}
print(Singleton.sharedInstance.getToken()) // STILL GET THE CORRECT VALUE
}
task.resume()
print(Singleton.sharedInstance.getToken()) // THE VALUE IS NOW NIL
class Singleton {
static let sharedInstance = Singleton()
var rToken:String?
func setToken( Token:String){
let lToken = Token
rToken = lToken
}
func getToken() -> String {
if self.rToken != nil {
return self.rToken!
}
return "0"
}
调用并且恢复单元中的值就消失了。下面是我的代码,请注意我现在只做了一个星期的快速:)
width >= 385
}
答案 0 :(得分:0)
正如KeranMarinov指出的那样,手术是异步完成的,所以你正处于竞争状态。基本上你的请求在后台线程上完成的时间比主线程步到下一行并检查值所花费的时间要长。
您可以做的是在主线程上发送您的请求,然后检查值:
dispatch_async(dispatch_get_main_queue(), {
myRequest()
})
print(Singleton.sharedInstance.getToken())
另外,让我们整理你对字符串的消毒:
let sanitizedData = String(data: data, encoding: .utf8)!
.replacingOccurrences(of: "\\", with: "")
.replacingOccurrences(of: "\"{", with: "{")
.replacingOccurrences(of: "}\"", with: "}")
.data(using: .utf8)!
最后,您还应该查看completion handlers,这是处理异步行为影响的好方法。