gpt4 book ai didi

ios - 捕获用户名以写入新帖子

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

当用户登录时,其 UID 将设置为 standardUserDefaults()。此外,用户的个人资料数据保存在名为其 uid 的子项下。

当用户创建帖子时,我想将他们的用户名/显示名称附加到帖子中。

我已经设置了一个函数来获取当前用户的用户名,但是每当我提交帖子时,似乎闭包并未被执行。

帖子模型:

class PostModel {
var postBody = String()
var creationDate = String()
var postUID = String()
var userName = String()

init(postBody: String) {
self.postBody = postBody
let dateObject = NSDate()
let formatDate = timeToString(dateObject)
self.creationDate = formatDate
let userID = NSUserDefaults.standardUserDefaults().valueForKey("uid") as! String
self.postUID = userID
self.userName = getUsername(userID)
}

// Used to convert the model to json compatible before saving
func postToDictionary() -> NSDictionary {
let jsonBody = postBody
let jsonDate = creationDate
let jsonUID = postUID
let jsonUsername = userName
let postAsDictionary = ["Body": jsonBody, "Timestamp": jsonDate, "UID": jsonUID, "Display Name": jsonUsername]
return postAsDictionary
}
}

以及获取用户名的函数:

func getUsername(withUID: String) -> String {
var userName = String()
DataService.ref.userRef.childByAppendingPath(withUID).observeSingleEventOfType(.Value, withBlock: { snapshot in
userName = snapshot.value.objectForKey("Display Name") as! String
})
return userName
}

最佳答案

我设置了登录功能来获取当前用户的显示名称并将其设置为有效的 standardUserDefaults 。我相信这是我的解决方案,除非有人有更好的建议

    @IBAction func loginButton(sender: AnyObject) {
if emailField != nil && passwordField != nil {

let emailAttempt = emailField.text!
let passwordAttempt = passwordField.text!
DataService.ref.baseRef.authUser(emailAttempt, password: passwordAttempt) {
error, authData in
if error != nil {
print("error in data check")
} else {
let returnUID = authData.uid
NSUserDefaults.standardUserDefaults().setValue(returnUID , forKey: "uid")
DataService.ref.userRef.childByAppendingPath(returnUID).childByAppendingPath("Display Name").observeSingleEventOfType(.Value, withBlock: { snapshot in
let UserDisplayName = snapshot.value as! String
NSUserDefaults.standardUserDefaults().setValue(UserDisplayName, forKey: "displayName")
self.performSegueWithIdentifier("loginSuccessSegue", sender: sender)

})

}
}
} else {
print("error")
return
}
}

关于ios - 捕获用户名以写入新帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37083988/

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