我是新手代码,我不知道如何摆脱我的可选值。我在某处读到这可能是我的问题。任何帮助都会很棒!
我一直在关注本教程:https://www.youtube.com/watch?v=Qyy8pJd4IWU
@IBAction func dropPhoto(sender: AnyObject) {
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [NSObject : AnyObject]?) {
self.dismissViewControllerAnimated(true, completion: nil)
let thumbnail = image.resizedImageWithContentMode(UIViewContentMode.ScaleAspectFit, bounds: CGSizeMake(400, 400), interpolationQuality: CGInterpolationQuality.High)
let imgData = UIImagePNGRepresentation(thumbnail)
let base64EncodedImage = imgData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
let uniqueReference = firebase?.childByAutoId()
uniqueReference!.setValue(base64EncodedImage)
let key = uniqueReference?.key
_ = mapView.userLocation.location
geofire!.setLocation(mapView.userLocation.location,forKey: key)
}
答案 0 :(得分:1)
每当看到此错误时,请查找“!”s
这里有两行包含force-unwrap
geofire!.setLocation(mapView.userLocation.location,forKey: key)
和
uniqueReference!.setValue(base64EncodedImage)
你应该能够通过简单地替换它来解决它!用一个? ,例如
geofire?.setLocation(mapView.userLocation.location,forKey: key)
只有当geoFire是实数值时才会调用setLocation,否则如果你还要处理nil情况,那么快速的方法是:
if let geoFire = geoFire {
geoFire.setLocation(mapView.userLocation.location, forKey: key)
}
else{
*do something*
}
答案 1 :(得分:1)
您还可以在功能开头添加assert
或precondition
检查firebase和geofire。这是第三种方法,它将检查这些值并停止在调试版本上执行,否则只需返回发布版本。这将使后面的方法调用firebase和geofire安全。
您仍然需要确定为什么您的某个引用意外为零并处理该情况。也许永远不会首先调用这个图像选择器函数,或者只是删除assertFailure
语句并让函数静默返回而不做任何事情。你的选择。
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [NSObject : AnyObject]?) {
guard let firebase = firebase else {
assertionFailure("Missing Firebase reference")
return
}
guard let geofire = geofire else {
assertionFailure("Missing Geofire reference")
return
}
self.dismissViewControllerAnimated(true, completion: nil)
let thumbnail = image.resizedImageWithContentMode(UIViewContentMode.ScaleAspectFit, bounds: CGSizeMake(400, 400), interpolationQuality: CGInterpolationQuality.High)
let imgData = UIImagePNGRepresentation(thumbnail)
let base64EncodedImage = imgData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
uniqueReference = firebase.childByAutoId()
uniqueReference.setValue(base64EncodedImage)
geofire.setLocation(mapView.userLocation.location,forKey: uniqueReference.key)
}