2016-09-27 87 views
0

根據Firebase DocschildByAutoId只要調用它就應該生成一個唯一的ID。Firebase Swift childByAutoId()

好了,但我在這裏使用它是這樣的:

let DeviceInfo = [ 
         "ImageUrl":profileImageUrl!, 
         "DeviceName":self.DeviceName.text!, 
         "Description":self.Description.text!, 
         "Category":self.itemSelected 
         ] as [String : Any] 

        self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).observeSingleEvent(of: .value, with: {(snapShot) in 
         if snapShot.exists(){ 
          let numberOfDevicesAlreadyInTheDB = snapShot.childrenCount 
          if numberOfDevicesAlreadyInTheDB < 3{ 
           let newDevice = String("Device\(numberOfDevicesAlreadyInTheDB+1)") 
           let userDeviceRef = self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid) 
           userDeviceRef.observeSingleEvent(of: .value, with: {(userDevices) in 
            if let userDeviceDict = userDevices.value as? NSMutableDictionary{ 

             userDeviceDict.setObject(DeviceInfo,forKey: newDevice as! NSCopying) 

             userDeviceRef.setValue(userDeviceDict) 
            } 
           }) 
          } 
          else{ 
           let alert = UIAlertController(title: "Sorry", message:"You can only add three devices", preferredStyle: .alert) 
           alert.addAction(UIAlertAction(title: "Ok", style: .default) { _ in }) 
           self.present(alert, animated: true){} 

          } 
         }else{ 
          self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).setValue(["Device1" : DeviceInfo]) 


          self.ref.child("UserDevices").childByAutoId().setValue([ 
           "ImageUrl":profileImageUrl!, 
           "DeviceName":self.DeviceName.text!, 
           "Description":self.Description.text!, 
           "Category":self.itemSelected, 
           "name": self.globalUserName, 
           "email":self.globalEmail , 
           "city": self.globalCity, 
           "phone": self.globalPhone 
           ] as [String : Any]) 

          let alert = UIAlertController(title: "Great", message:"Device has beed added succssfully", preferredStyle: .alert) 
          alert.addAction(UIAlertAction(title: "Ok", style: .default) { _ in }) 
          self.present(alert, animated: true){} 
                 } 
        }) 

        // 
       } }) 
     } 

這是一個按鈕用於將設備添加到火力地堡的一部分。

如果有小於3級的設備,用戶可以添加(其他情況下,這裏),否則,警報應該呈現給用戶「,如果之前情況下,這個別人的(你可以只添加3設備) 。

當我添加第一個設備時,上面的兩個字典已添加到Firebase。但第二次,當我嘗試添加第二個設備時,第一個字典已被添加,但不包含第二個包含childByAutoId的字典。

這聽起來很奇怪。 childByAutoId可以給每個註冊用戶一個ID嗎?

+0

我不問如何添加限制! – Mariah

+0

我問爲什麼childByAutoId()第二次添加設備時沒有生成自動ID? – Mariah

+0

任何人,可以給我任何建議嗎?請。 – Mariah

回答

0

我在問爲什麼childByAutoId()沒有生成自動ID第二個 我添加了一個設備?

看起來您只在「設備」爲空時(即snapShot.exists()返回false)時才致電childByAutoId()。一旦你填充了「設備」,那條線就不會再被擊中。

相關問題