gpt4 book ai didi

ios - 火力地堡, swift : `runTransactionBlock()` returns null

转载 作者:行者123 更新时间:2023-11-28 12:40:51 28 4
gpt4 key购买 nike

每次我运行 runTransactionBlock 它都会给我 null,尽管那个位置有一个节点:-

FIRMutableData (top-most transaction) (null)

在行:- print(totalPost)

func updateTotalNoOfPost(){


let prntRef = FIRDatabase.database().reference().child("TotalPosts")
prntRef.observeSingleEventOfType(.Value, withBlock: {(totalSnap) in

if totalSnap.exists(){

prntRef.child("noOfTotalPost").runTransactionBlock({ (totalPost: FIRMutableData) -> FIRTransactionResult in

print(FIRAuth.auth()!.currentUser!.uid)//Giving me correct userID
print(totalPost)//<Null>
print(prntRef.child("noOfTotalPost"))//Giving me correct path to that node

totalPost.value = totalPost.value as! Int + 1
return FIRTransactionResult.successWithValue(totalPost)
}, andCompletionBlock: { (err, TF, snap) in

print(err?.localizedDescription)
print(TF)
print(snap!.value)
FIRTransactionResult.abort()// Am i using this right?
})
}else{

prntRef.setValue(["noOfTotalPost": 1])

}
})
}

我的 JSON 树结构是这样的:-

 {
"TotalPosts" : {
"noOfTotalPost" : 1
},
"Users" : {
"FBLXPOxBomakPCQuDTilGC7Becu2" : {...},
"1DASWPOxBomakPCdasd1d123au6" : {...},...}}

我正在为我的数据库使用默认的安全规则:-

      {
"rules": {
".read": "auth != null",
".write": "auth != null"

}
}

我只想在每次任何用户创建帖子时增加一个 noOfTotalPost 子节点的值:-

我已经有了使用 observeSingleEventOfType 的解决方法。:

    let prntRef = FIRDatabase.database().reference().child("TotalPosts")
prntRef.child("noOfTotalPost").observeSingleEventOfType(.Value, withBlock: {(totalSnap) in

if totalSnap.exists(){

if let tNo = totalSnap.value as? Int{

prntRef.child("noOfTotalPost").setValue(tNo+1)//Working Fine

}
})
}else{

prntRef.setValue(["noOfTotalPost": 1])

}
})

但无法弄清楚为什么 runTransactionBlock 不起作用!

最佳答案

正如@Frank 在评论中所说,runTransactionBloack 最初返回 NSNull 是预期的行为,但如果该位置已经有一个值,它会再次触发。如果在更新值时发生冲突,它将再次触发。

代码:-

func updateTotalNoOfPost(completionBlock : (() -> Void)){


let prntRef = FIRDatabase.database().reference().child("TotalPosts")

prntRef.child("noOfTotalPost").runTransactionBlock({ (noOfPosts) -> FIRTransactionResult in
if let totalPost = noOfPosts.value as? Int{

noOfPosts.value = totalPost + 1
return FIRTransactionResult.successWithValue(noOfPosts)
}else{

return FIRTransactionResult.successWithValue(noOfPosts)

}
}, andCompletionBlock: {(error,completion,snap) in

print(error?.localizedDescription)
print(completion)
print(snap)
if !completion {

print("The value wasn't able to Update")
}else{

completionBlock()
}
})

}

基本概念:-

Data in transaction is null

关于ios - 火力地堡, swift : `runTransactionBlock()` returns null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39443839/

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