Rob*_*lor 3 firebase swift firebase-authentication firebase-realtime-database
我查看了几个小时的代码和注释,我很难找到任何可以帮助我在使用firebase的swift应用程序中对一个对象进行upvoting和downvoting的文档.
我有一个照片库,我希望为图像添加一个Instagram风格的upvote.用户已使用firebase auth登录,因此我有他们的用户ID.
我只是在努力想出这个方法以及需要在firebase中设置哪些规则.
任何帮助都是极好的.
pka*_*zak 12
我将描述我如何在社交网络应用程序Impether中使用Swift和实现这样的功能Firebase.
由于upvoting和downvoting是类似的,我将仅描述upvoting.
一般的想法是将一个upvotes计数器直接存储在与计数器相关的图像数据相对应的节点中,并使用事务写入来更新计数器值,以避免数据中的不一致.
例如,假设您在路径中存储单个图像数据/images/$imageId/,其中$imageId是用于标识特定图像的唯一ID - 例如,可以通过Firebase for iOS中包含的函数childByAutoId生成它.然后,与该节点上的单张照片对应的对象如下所示:
$imageId: {
'url': 'http://static.example.com/images/$imageId.jpg',
'caption': 'Some caption',
'author_username': 'foobarbaz'
}
Run Code Online (Sandbox Code Playgroud)
我们想要做的是为此节点添加一个upvote计数器,因此它变为:
$imageId: {
'url': 'http://static.example.com/images/$imageId.jpg',
'caption': 'Some caption',
'author_username': 'foobarbaz',
'upvotes': 12,
}
Run Code Online (Sandbox Code Playgroud)
当您创建新图像时(可能是在用户上传图像时),您可能希望0根据您想要实现的内容初始化upvote计数器值或其他常量.
在更新特定的upvotes计数器时,您希望使用事务以避免其值的不一致(当多个客户端想要同时更新计数器时,可能会发生这种情况).
幸运的是,处理事务中写道Firebase,并Swift是超级简单:
func upvote(imageId: String,
success successBlock: (Int) -> Void,
error errorBlock: () -> Void) {
let ref = Firebase(url: "https://YOUR-FIREBASE-URL.firebaseio.com/images")
.childByAppendingPath(imageId)
.childByAppendingPath("upvotes")
ref.runTransactionBlock({
(currentData: FMutableData!) in
//value of the counter before an update
var value = currentData.value as? Int
//checking for nil data is very important when using
//transactional writes
if value == nil {
value = 0
}
//actual update
currentData.value = value! + 1
return FTransactionResult.successWithValue(currentData)
}, andCompletionBlock: {
error, commited, snap in
//if the transaction was commited, i.e. the data
//under snap variable has the value of the counter after
//updates are done
if commited {
let upvotes = snap.value as! Int
//call success callback function if you want
successBlock(upvotes)
} else {
//call error callback function if you want
errorBlock()
}
})
}
Run Code Online (Sandbox Code Playgroud)
上面的剪辑实际上几乎就是我们在制作中使用的代码.我希望它可以帮助你:)
| 归档时间: |
|
| 查看次数: |
1806 次 |
| 最近记录: |