【问题标题】:Swift 3 found nil when Firebase DB persistence is enabled启用 Firebase DB 持久性后,Swift 3 发现 nil
【发布时间】:2017-03-30 10:07:49
【问题描述】:

在我的应用程序中,我使用 Firebase db 来存储我的数据,一切正常,我的 tableview 填充了来自 db 的数据。但是我发现在初始启动时下载数据很慢,所以我在 AppDelegate 中启用了持久性。当我这样做并运行应用程序时,它在加载时崩溃并意外发现 nil 错误。

FIRDatabase.database().persistenceEnabled = true

是我在 didFinishLaunching 部分下添加到 AppDelegate 的行。

这个类在我标记的那一行出现了错误

import Foundation
import FirebaseDatabase
import CoreLocation

struct newTracks {

//Declerations
var locationManager = CLLocationManager()
let name: String!
let lat: Double!
let lon: Double!
let countryImage: String!
let link: String!
let ref: FIRDatabaseReference?
let distance: Double


//Initialize
init(name: String, trackId: Int, postcode: String, trackType: String, trackURL: String, locID: Int, lat: Double, lon: Double, phoneNumber: String, email: String, rating: Double, numrating: Double, totalrating: Double, countryImage: String, link: String, distance: Double) {
    self.name = name
    self.ref = nil
    self.lat = lat
    self.lon = lon
    self.countryImage = countryImage
    self.link = link
    self.distance = distance
 }

//Initialize data from Firebase
init(snapshot: FIRDataSnapshot) {

    let snapshotValue = snapshot.value as! [String: AnyObject]
    name = snapshotValue["name"] as! String
    lat = snapshotValue["lat"]as! Double
    lon = snapshotValue["long"]as! Double
    ref = snapshot.ref
    countryImage = snapshotValue["country"] as! String   <--  Unexpectedly found nil
    link = snapshotValue["link"] as! String

    let currentLat = self.locationManager.location!.coordinate.latitude
    let currentLon = self.locationManager.location!.coordinate.longitude
    let myLocation = CLLocation(latitude: currentLat, longitude: currentLon)
    let loc = CLLocation(latitude: lat, longitude: lon)
    let distanceInMiles = round(myLocation.distance(from: loc) / 1609.34)
    distance = distanceInMiles

}

func toAnyObject() -> Any {
    return [
        "name": name,
        "lat": lat,
        "lon": lon,
        "countryImage": countryImage,
        "link": link,
        "distance": distance
    ]

 }

}

我不明白为什么当没有打开持久性时它可以正常工作,但是当我启用它时它会崩溃。非常感谢任何帮助。

【问题讨论】:

  • 为您的问题添加更多标签。如“Firebase”等。它将帮助您更快地得到答案
  • 检查更新的答案

标签: swift xcode firebase firebase-realtime-database


【解决方案1】:

您已将 countryImage 标记为可选值。您的快照可能对"country" 没有价值。 尝试改变:

let countryImage: String!

到:

let countryImage: String

编辑: 也许,当您打开持久性时,您的应用程序正在从缓存中获取旧数据。并且此数据在快照值中没有 ["country"]。所以它发现 nil -> 抛出错误。通过断点检查您的快照值。并检查它是否对国家/地区有价值

希望对你有帮助

【讨论】:

    【解决方案2】:

    我已经通过从手机上卸载应用程序解决了这个问题,这清除了旧的缓存数据,现在似乎可以加载了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-30
      • 2016-09-13
      • 2018-11-10
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      相关资源
      最近更新 更多