gpt4 book ai didi

ios - 在 Firebase 中保存数组

转载 作者:行者123 更新时间:2023-11-28 21:25:09 24 4
gpt4 key购买 nike

我使用 Firebase 3.0 作为我的后端,我需要将我的每个 user.uid 保存在一个单独的子项中,它需要是一个 NSArray,然后使用 for 循环检索该数组!

这就是我保存数据的方式:我为 FIRController 创建了一个单独的类,它处理数据库和存储的所有存储和检索。

func signUpUserWithBasicInfo(emailId : String! , password : String!, username : String!, age : String, gender : String!, backpackerType : String, info : [String : AnyObject], completionBlock : (() -> Void)){

print("fir signup did recieve")
FIRAuth.auth()?.createUserWithEmail(emailId, password: password, completion: {
user,error in

if error != nil{
print("error encountered while backend email signup Handshake : \(error)")
print("")
self.delegate.firShowAlert("Error signing you up", Message: "Please check your network or this email already exist!")

}else{
print("uploading database")
self.profilePictureUploading(info, completionBlock: {

FIRControllerClass.ref.child("UserProfile").child(user!.uid).setValue([
"username" : username,
"email" : emailId,
"age" : age,
"gender" : gender,
"password" : password,
"typeOfBackpacker" : backpackerType
])

completionBlock()

})
}
})
}

func profilePictureUploading(infoOnThePicture : [String : AnyObject],completionBlock : (()->Void)) {

if let referenceUrl = infoOnThePicture[UIImagePickerControllerReferenceURL] {
print(referenceUrl)
let assets = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl as! NSURL], options: nil)
print(assets)
let asset = assets.firstObject
print(asset)
asset?.requestContentEditingInputWithOptions(nil, completionHandler: { (ContentEditingInput, infoOfThePicture) in

let imageFile = ContentEditingInput?.fullSizeImageURL
print("imagefile : \(imageFile)")

let filePath = FIRAuth.auth()!.currentUser!.uid + "/\(Int(NSDate.timeIntervalSinceReferenceDate() * 1000))/\(imageFile!.lastPathComponent!)"
print("filePath : \(filePath)")

FIRControllerClass.storageRef.child("ProfilePictures").child(filePath).putFile(imageFile!, metadata: nil, completion: { (metadata, error) in

if error != nil{

print("error in uploading image : \(error)")
self.delegate.firShowAlert("Error Uploading Your Profile Pic", Message: "Please check your network!")
}

else{

print("metadata in : \(metadata!)")
print(metadata?.downloadURL())
print("The pic has been uploaded")
print("download url : \(metadata?.downloadURL())")

self.uploadSuccess(metadata!, storagePath: filePath)

completionBlock()

}

})
})

} else {
print("No reference URL found!")
}
}

我如何在后端创建一个用作数组的子项,以及如何检索该数组?

我的 firebase JSON 结构:-

{
"UserId" : [ 1,
"Sq5EDvVOsQWkLylEx3GrBdEsIN92",
"xC4jCJmobUcqghq8C3SI1XT0UPk1",
"D8QmnOSH6vRYiMujKNXngzhdn992",
"riHjon6wknOmALwf0Z0Ri5aOMA82",
"fKqlb88MKsYCE43xy7D51qH6jqH3",
"aCgAFAGDIgWRSUu9a2aMo9HtnnD3",
"iicKACGo8RaeTSEggKPB0sU2Bme2",
"qJ2c8AcEYzVkJKLl13N92tyKnbz2"
],
"UserProfile" : {
"D8QmnOSH6vRYiMujKNXngzhdn992" : {
"age" : "12",
"email" : "dummy1@gmail.com",
"gender" : "f",
"password" : "123454321",
"typeOfBackpacker" : "dummy",
"username" : "duummyy1"
},
"Sq5EDvVOsQWkLylEx3GrBdEsIN92" : {
"age" : "121",
"email" : "ghfgh@gnag.com",
"gender" : "gjhg",
"password" : "123454321",
"typeOfBackpacker" : "chef",
"username" : "hgfgh"
},
"aCgAFAGDIgWRSUu9a2aMo9HtnnD3" : {
"age" : "24",
"email" : "cathydurrant@gmail.com",
"gender" : "F",
"password" : "123454321",
"typeOfBackpacker" : "Group",
"username" : "Cathy"
},
etc
}

我还需要在我的数据库(数组)中添加一个no of friends数组。我使用for循环的唯一原因是我可以向我的用户显示每个用户的详细信息(除了来自他/她自己)使用我在我的数据库中创建的 userId 数组,这实际上是我的每个用户数据库的父节点。

这就是我在数据库中附加 UserId 的方式:-

func retrieveUserIdsArray(completionBlock : ((appendedArr : NSMutableArray) -> Void)){

var appendedArray : NSMutableArray = []

FIRControllerClass.ref.child("UserId").observeEventType(FIRDataEventType.Value, withBlock: {(snapshot) in

if let userIdDetails = snapshot.value as? NSMutableArray{

userIdDetails.addObject((FIRAuth.auth()?.currentUser?.uid)!)
appendedArray = userIdDetails

completionBlock(appendedArr: appendedArray)

}
})
}

在此函数中调用:-

    func signUpUserWithBasicInfo(emailId : String! , password : String!, username : String!, age : String, gender : String!, backpackerType : String, info : [String : AnyObject], completionBlock : (() -> Void)){

print("fir signup did recieve")

FIRAuth.auth()?.createUserWithEmail(emailId, password: password, completion: {
user,error in

if error != nil{

print("error encountered while backend email signup Handshake : \(error)")

print("")

self.delegate.firShowAlert("Error signing you up", Message: "Please check your network or this email already exist!")

}else{

print("uploading database")

self.profilePictureUploading(info, completionBlock: {

FIRControllerClass.ref.child("UserProfile").child(user!.uid).setValue([
"username" : username,
"email" : emailId,
"age" : age,
"gender" : gender,
"password" : password,
"typeOfBackpacker" : backpackerType
])


var a = 0

self.retrieveUserIdsArray({ (appendedArr) in

a += 1

print("The appended array is : \(appendedArr)")

if a == 1{

FIRControllerClass.ref.child("UserId").setValue(appendedArr)

}else{

completionBlock()

}
})
})
}
})
}

我使用 a 变量的原因是为了解决它引起的无限循环(我知道它只是一个 hack,现在..)

欢迎任何更好的方法来解决这个问题!..

最佳答案

数组在 Firebase 中可能具有挑战性,因为不能直接访问或修改单个元素。您要么读取整个数组,要么写入整个数组。

我建议更改结构以更好地匹配您想要的数据并完全避免数组:

"UserProfile" : {
"D8QmnOSH6vRYiMujKNXngzhdn992" : {
"age" : "12",
"email" : "dummy1@gmail.com",
"gender" : "f",
"password" : "123454321",
"typeOfBackpacker" : "dummy",
"username" : "duummyy1"
"friend_count": 10
"friend_of"
"aCgAFAGDIgWRSUu9a2aMo9HtnnD3": true
},

然后一个简单的深度查询将返回您需要的一切(Firebase v2)

let myUid = "aCgAFAGDIgWRSUu9a2aMo9HtnnD3"
let path = ("friend_of/\(myUid)") // equals friend_of/aCgAFAGDIgWRSUu9a2aMo9HtnnD3
var userIdArray = [String]()
userProfileRef.queryOrderedByChild(path)
.queryEqualToValue(true)
.observeSingleEventOfType(.Value, withBlock: { snapshot in
for child in snapshot.children {
let userId = child.key as String
userIdArray.append(userId)
}
//loop is done, now we have an array of userIds that are friends
})

代码返回我的 friend 的每个用户 (myUid)

我还添加了一个“ friend 计数”节点,它只记录该用户的 friend 数量。添加 friend 时,增加值,删除时减少值。很快

myUid.child("friend_count").setValue(updated_count)

此代码还避免了循环、回调和额外的完成 block ,因为它依赖于 Firebase 来获取数据,并在完成时通知我们。

如果你真的非常想读取一个数组节点(不推荐)

    let myRef = self.myRootRef.child("array_node")
myRef.observeSingleEventOfType(.Value, withBlock: { snapshot in

let a = snapshot.value as! NSArray
print(a) //a an NSArray

let b = (a as Array).filter {$0 is String}

print(b) //b is a Swift Array

print( b[1] )
})

关于ios - 在 Firebase 中保存数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38369382/

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