gpt4 book ai didi

swift - 如果在 URLSession 之后呈现 View ,UIButton 标签会消失

转载 作者:行者123 更新时间:2023-11-30 11:48:08 24 4
gpt4 key购买 nike

我正在制作一个社交应用程序,它通过 URLSession 检查用户是否登录。

所以我创建了 3 个 ViewController

  1. 自定义启动屏幕VC
  2. 登录VC
  3. MainVc

CustomLaunchScreenVC:

View 出现后,我调用 checkIfSignedIn() 函数,该函数检查用户默认值中是否保存了 session 值。

如果NOT,则加载LoginVC

如果YES它调用另一个函数:loginWithSession(uid, session)

这个函数(loginWithSession)可能会因为里面有一个URLRequest而延迟。

它在网站上检查 session 是否有效,然后调用 goToMainVC() 或 goToLoginVC() 函数

<小时/>

现在的问题是,如果有一个已保存的 session ,但它无效,那么应用程序应该转到 SignInVC,它确实如此,但该 VC 上的按钮标签消失了,我不知道为什么.

(我尝试了一些方法,在从 loginWithSession() 函数中删除 URLSession Task 后,问题解决了,按钮也正常了。但我真的需要那个 URLSession 函数..)

所以可能是因为互联网连接造成了一些延迟,然后提交 VC 导致了类似的问题。

这是 CustomLaunchScreenVC 的代码(简化):

class CustomLaunchScreenVC : UIViewController {


override func viewDidAppear(_ animated: Bool) {
checkIfSignedIn()
}

func checkIfSignedIn(){
let uid = defaults.integer(forKey: "uid")
let session = defaults.string(forKey: "session")
if uid != nil && session != nil {
loginWithSession(session: session, uid: uid) { response in
if let response = response {

if (response!.loggedIn == "yes"){
self.goToMainVC()
} else {
self.goToLoginVC() // This does NOT work, UIButtons' labels are NOT loading, and I don't know why :(
}
}
}
} else {
// there is no saved session so user is not logged in
self.goToLoginVC() // This does works, UIButtons' labels are loading
}
}




func loginWithSession(session: String, uid: Int, completion: @escaping (CustomTypeArray??)->()){

let connectUrl = URL(string: "http://website.com/common/php/sessionLogin.php")
var request = URLRequest(url: connectUrl!)
request.httpMethod = "POST"
let postString = "userId=\(uid)&session=\(session)"
request.httpBody = postString.data(using: String.Encoding.utf8)

let task = URLSession.shared.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) in

//Simplified the code
if (data.loggedin == "yes"){
return completion(CustomTypeArray(loggedIn : "yes"))
} else {
return completion(CustomTypeArray(loggedIn : "no"))
}
}
task.resume()

}



func goToLoginVC(){
let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
self.present(loginVC, animated: false)
}
func goToMainVC(){
let mainVC = self.storyboard?.instantiateViewController(withIdentifier: "MainVC") as! MainVC
self.present(mainVC, animated: false)
}
}

问题视频:Video

最佳答案

@rmaddy 帮助了我,谢谢!

解决方案是将所有 UI 代码移至主队列

DispatchQueue.main.async(execute: {() -> Void in
self.goToSigninVC()
})

关于swift - 如果在 URLSession 之后呈现 View ,UIButton 标签会消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48601612/

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