我想在tableviewcell的所有单元格中添加一个关注/跟随按钮(链接到当前用户正在关注的用户-与instagram关注者列表类似)。
代码运行,但是当我单击“关注者”按钮将我带到表视图时,我不断收到错误消息“线程1:致命错误:在展开可选值时意外发现nil”-希望有任何帮助知道我在做什么错。
表格视图单元格中的代码:
@IBOutlet weak var followersFollowButton: UIButton!
var user: UserModel? {
didSet {
updateView()
}
}
func updateView() {
if user!.isFollowing! {
configureUnFollowButton()
} else {
configureFollowButton()
}
}
视图控制器中的代码:
@IBOutlet weak var tableView: UITableView!
var users: [UserModel] = []
func loadusers() {
let ref = Database.database().reference()
guard let currentUser = Auth.auth().currentUser?.uid else { return }
let followersRef = ref.child("followers").child(currentUser) //retreives all nodes in the following node
followersRef.observe(DataEventType.value, with: { snapshot in
print(snapshot.children.allObjects)
for child in snapshot.children { //build the array of keys
let snap = child as! DataSnapshot
let key = snap.key
let userRef = ref.child("users").child(key) //get the user name and profile image from the users node
userRef.observeSingleEvent(of: .value, with: { snapshot in
let user = UserModel()
user.fullname = snapshot.childSnapshot(forPath: "fullname").value as? String
user.profileImageUrl = snapshot.childSnapshot(forPath: "profileImageUrl").value as? String
//line below is where i am getting the error
self.isFollowing(userId: user.id!, completed: { (value) in
user.isFollowing = value
self.users.append(user)
self.tableView.reloadData()
})
})
}
})
}
func isFollowing(userId: String, completed: @escaping (Bool) -> Void) {
Api.Follow.isFollowing(userId: userId, completed: completed)
}
遵循Api的代码:
var REF_FOLLOWERS = Database.database().reference().child("followers")
func isFollowing(userId: String, completed: @escaping (Bool) -> Void) {
REF_FOLLOWERS.child(userId).child(Api.User.CURRENT_USER!.uid).observeSingleEvent(of: .value, with: {
snapshot in
if let _ = snapshot.value as? NSNull {
completed(false)
} else {
completed(true)
}
})
}
预先感谢
答案 0 :(得分:0)
您要强制展开包含nil
的可选值。
您应该在if let
函数中使用guard let
或updateView()
语句。
此外,let snap = child as! DataSnapshot
可能会失败,而user.id!
会出现nil
值的情况(鉴于错误消息和您的评论,后者会发生这种情况)。您应该重写它们以安全地处理nil
值情况。
最佳做法是不惜一切代价避免使用力解开/爆炸操作符(!
)。