所以我的应用程序运行正常;我使用以下方式将数据库持久保存在本地:
Database.database().isPersistenceEnabled = true
我什么都没做,但是突然之间它开始返回一个空快照。当我注释掉该行时,一切都再次正常运行,并且界面中的标签正确显示,并且该值在多个设备之间正确同步。这是我的viewDidLoad的代码片段:
import UIKit
import Firebase
import FirebaseDatabase
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var returnedName: UILabel!
@IBOutlet weak var scannedURLTextField: UITextField!
@IBOutlet weak var reentries: UILabel!
@IBOutlet weak var visitors: UILabel!
@IBOutlet weak var ticketType: UILabel!
@IBOutlet weak var statusImage: UIImageView!
@IBOutlet weak var entryOrReentrySwitch: UISwitch!
var qrDecodedURL : String!
var ticketNumber : String!
var eventID : String!
var numberOfAttendees: String!
var urlDictionary = [String : Any]()
var attendeeRef: DatabaseReference!
var ticketRef : DatabaseReference!
var entries : DatabaseReference!
var entriesRef : DatabaseReference!
var reentriesRef : DatabaseReference!
var entriesInt : Int!
var reentriesInt : Int!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
Database.database().isPersistenceEnabled = true
attendeeRef = Database.database().reference(withPath: "attendees")
ticketRef = Database.database().reference(withPath: "tickets")
entriesRef = Database.database().reference(withPath: "entries")
reentriesRef = Database.database().reference(withPath: "reentries")
self.scannedURLTextField .becomeFirstResponder()
scannedURLTextField.inputView=UIView()//create dummy view to supress keyboard
// Incresase size of switch
entryOrReentrySwitch.transform = CGAffineTransform(scaleX: 1.5, y: 1.5);
//monitor for changes in entries
entriesRef.child("entries").observe(.value, with: { (snapshot) in
print(snapshot);
self.visitors.text = "Visitors: \(snapshot.value as! String)"
let tempValue = snapshot.value as! String
self.entriesInt = Int(tempValue)
})
//Monitor for changes in reentries
reentriesRef.child("reentries").observe(.value, with: { (snapshot) in
// print(snapshot);
self.reentries.text = "Reentries: \(snapshot.value as! String)"
})
statusImage.image = UIImage.init(named: "scanQR.png")
}
生成的错误是:
Could not cast value of type 'NSNull' (0x1fb2f3270) to 'NSString' (0x1fb2fcab8).
2019-10-12 18:05:54.061687-0700 VIM Tickets[621:97014] Could not cast value of type 'NSNull' (0x1fb2f3270) to 'NSString' (0x1fb2fcab8).
在条目更改部分的监视器中的self.visitors.text = "Visitors: \(snapshot.value as! String)"
上失败。同样,当我注释掉数据库持久性行时,一切工作都很好,并且快照中有数据。我什至将其移至AppDelegate,但结果相同。
为什么在之前的持久性工作之前会发生这种情况,我有些茫然。任何建议将不胜感激!
答案 0 :(得分:0)
启用磁盘持久性后,Firebase客户端会立即使用其对该节点知道的当前值来启动。在您的情况下,听起来好像认为值是null
,因此触发该值。如果您与服务器建立了连接,那么稍后它会使用从服务器获得的正确值触发。
处理这种情况的通常方法是先处理check whether the snapshot exists,然后再处理其内容。