gpt4 book ai didi

ios - 当我运行我的应用程序时,我收到此错误。线程 1 : Fatal error: Unexpectedly found nil while unwrapping an Optional value

转载 作者:行者123 更新时间:2023-11-30 11:00:29 24 4
gpt4 key购买 nike

每当我运行我的应用程序时,它总是在显示 currentUserID 的任何地方崩溃。不知道为什么。 我打印了 currentUserID 值及其 nil。 我该如何纠正它,以便它可以很好地运行我的应用程序。如果需要,我可以分享其余的代码。

import UIKit
import MapKit
import CoreLocation
import Firebase
//import FirebaseDatabase

enum AnnotationType {
case pickup
case destination
case driver
}

enum ButtonAction {
case requestRide
case getDirectionsToPassenger
case getDirectionToDestination
case startTrip
case endTrip
}

class HomeVC: UIViewController, Alertable {

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var centerMapBtn: UIButton!
@IBOutlet weak var destinationTextField: UITextField!
@IBOutlet weak var destinationCircle: UIView!
@IBOutlet weak var cancelBtn: UIButton!
@IBOutlet weak var actionBtn: UIButton!




var delegate: CenterVCDelegate?

var manager: CLLocationManager?

let currentUserId = Auth.auth().currentUser?.uid
// "IRD70YtgEyWRpaH8LkkjHZmjXPo1"


var ref: DatabaseReference!

var regionRadius: CLLocationDistance = 1000

var tableView = UITableView()

var matchingItems: [MKMapItem] = [MKMapItem]()

var route: MKRoute!

var selectedItemPlacemark: MKPlacemark? = nil

var actionForButton: ButtonAction = .requestRide

override func viewDidLoad() {
super.viewDidLoad()



ref = Database.database().reference()
// print(ref.child("users").value(forKey: "users"))
self.ref.child("userse").childByAutoId().setValue("wise")

self.ref.child("users").child("sdsd").setValue("data")


// print(Auth.auth().currentUser?.uid)
// print(currentUserId)


manager = CLLocationManager()
manager?.delegate = self
manager?.desiredAccuracy = kCLLocationAccuracyBest

checkLocationAuthStatus()

mapView.delegate = self
destinationTextField.delegate = self

centerMapOnUserLocation()

DataService.instance.REF_DRIVERS.observe(.value, with: { (snapshot) in
self.loadDriverAnnotationFromFB()



DataService.instance.passengerIsOnTrip(passengerKey: self.currentUserId!, handler: { (isOnTrip, driverKey, tripKey) in
if isOnTrip == true {
self.zoom(toFitAnnotationsFromMapView: self.mapView, forActiveTripWithDriver: true, withKey: driverKey)
}
})
})

cancelBtn.alpha = 0.0
UpdateService.instance.observeTrips { (tripDict) in
if let tripDict = tripDict {
let pickupCoordinateArray = tripDict["pickupCoordinate"] as! NSArray
let tripKey = tripDict["passengerKey"] as! String
let acceptanceStatus = tripDict["tripIsAccepted"] as! Bool

if acceptanceStatus == false {
//Broadcast to all driver
DataService.instance.driverIsAvailable(key: self.currentUserId!, handler: { (available) in
//check for errors
if let available = available {
if available == true {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let pickupVC = storyboard.instantiateViewController(withIdentifier: "PickupVC") as? PickupVC
pickupVC?.initData(coordinate: CLLocationCoordinate2D(latitude: pickupCoordinateArray[0] as! CLLocationDegrees, longitude: pickupCoordinateArray[1] as! CLLocationDegrees), passengerKey: tripKey)
self.present(pickupVC!, animated: true, completion: nil)
}
}

})
}
}
}

}



override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if self.currentUserId == nil {
print("login")
}
DataService.instance.userIsDriver(userKey: self.currentUserId!, handler: { (status) in
if status == true {
self.buttonsForDriver(areHidden: true)
}
})

DataService.instance.REF_TRIPS.observe(.childRemoved, with: { (removedTripSnapshot) in
let removedTripDict = removedTripSnapshot.value as? [String: AnyObject]
if removedTripDict?["driverKey"] != nil {
DataService.instance.REF_DRIVERS.child(removedTripDict?["driverKey"] as! String).updateChildValues(["driverIsOnTrip": false])
}
DataService.instance.userIsDriver(userKey: self.currentUserId!, handler: { (isDriver) in
if isDriver == true {
// Remove Overlays and annotation and hide request ride and cancel button
self.removeOverlaysAndAnnotations(forDrivers: false, forPassengers: true)
} else {
self.cancelBtn.fadeTo(alphaValue: 0.0, withDuration: 0.2)
self.destinationTextField.isUserInteractionEnabled = true
self.destinationTextField.text = ""

// Remove all map annotation and overlays
self.removeOverlaysAndAnnotations(forDrivers: false, forPassengers: true)
self.centerMapOnUserLocation()
}
})
})
DataService.instance.driverIsOnTrip(driverkey: self.currentUserId!, handler: { (isOnTrip, driverKey, tripKey) in
if isOnTrip == true {
DataService.instance.REF_TRIPS.observeSingleEvent(of: .value, with: { (tripSnapshot) in
if let tripSnapshot = tripSnapshot.children.allObjects as? [DataSnapshot] {
for trip in tripSnapshot {
if trip.childSnapshot(forPath: "driverKey").value as? String == self.currentUserId! {
let pickupCoordinateArray = trip.childSnapshot(forPath: "pickupCoordinate").value as! NSArray
let pickupCoordinate = CLLocationCoordinate2D(latitude: pickupCoordinateArray[0] as! CLLocationDegrees, longitude: pickupCoordinateArray[1] as! CLLocationDegrees)
let pickupPlacemark = MKPlacemark(coordinate: pickupCoordinate)
self.dropPinFor(placemark: pickupPlacemark)
self.searchMapKitForResultsWithPolyline(forOriginMapItem: nil, withDestinationMapItem: MKMapItem(placemark: pickupPlacemark))
self.setCustomRegion(forAnnotationType: .pickup, withCoordinate: pickupCoordinate)

self.actionForButton = .getDirectionsToPassenger
self.actionBtn.setTitle("GET DIRECTION", for: .normal)

// Fade in the action button
self.buttonsForDriver(areHidden: false)

}
}
}
})

最佳答案

有几个问题需要解决,然后才是核心问题。

第一件事是Auth.auth().currentUser?是一个可选的 - 意味着它可以有一个值,也可以为零。这样做..

let currentUserId = Auth.auth().currentUser?.uid

告诉你的代码,无论它有值还是nil,都尝试将.uid分配给currentUserId。

通过安全地解包选项来保护您的代码

guard let currentUser = Auth.auth().currentUser else {return}
//now you can access currentUser as it won't be nil

if let currentUser = Auth.auth().currentUser {
print("user is authenticated and currentUser is not nil")
} else {
print("not authenticated")
}

现在问题的核心是,据我所知,您根本没有对用户进行身份验证,这需要在访问 Auth.auth().currentUser 之前进行

这是一个带有错误处理的完整身份验证函数

func authUser(user: String, pw: String) {
Auth.auth().signIn(withEmail: user, password: pw, completion: { (auth, error) in
if let x = error {
let err = x as NSError
switch err.code {
case AuthErrorCode.wrongPassword.rawValue:
print("wrong password")
case AuthErrorCode.invalidEmail.rawValue:
print("invalued email")
default:
print("unknown error")
}
} else {
if let user = auth?.user { //note; safely unwrap optional
print("uid: \(user.uid)")
}
}
})
}

关于ios - 当我运行我的应用程序时,我收到此错误。线程 1 : Fatal error: Unexpectedly found nil while unwrapping an Optional value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53440677/

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