After the recent Swift update, I have been trying to debut a few lines of code and don't seem to be understanding what's wrong..
The lines are
PFGeoPoint.geoPointForCurrentLocationInBackground {
with the error message "Cannot invoke 'geoPointForCurrentLocationInBackground' with an argument list of type '((PFGeoPoint", NSError!) -> Void)'"
The second line is
PFUser.logInWithUsernameInBackground(username:usernameTextField.text, password:passwordTextField.text, target: self) {
With the error "Extra argument 'target' in call"
I've tried looking online and debugging these, but I honestly have no idea what's going on. It seems to be an error in the parse code and I'm not sure why that is...
Edit: I fixed second error I was having. code:
PFUser.logInWithUsernameInBackground(usernameTextField.text, password:passwordTextField.text) {
Start from Swift 1.2, the Failable Casts is introduced. you can use the PFGeoPoint.geoPointForCurrentLocationInBackground method like the following:
If you're quite sure that the downcasting will succeed, you can use as! to force the cast:
PFGeoPoint.geoPointForCurrentLocationInBackground {
(point:PFGeoPoint!, error:NSError!) -> Void in
if (error == nil) {
println(point)
} else {
println(error)
}
}
If you're not sure if the casting will succeed, just use the as? operator. By using as?, it returns an optional value, but in case the downcasting fails, the value will be nil.
PFGeoPoint.geoPointForCurrentLocationInBackground {
(point:PFGeoPoint?, error:NSError!) -> Void in
if (error == nil) {
if let myPoint = point {
println(myPoint)
}
} else {
println(error)
}
}
Related
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
I am trying to download image from Firebase storage.
func downloadThumbnail(thumbnail: String) -> URL {
var thumb: URL!
let _ = DataService.dataService.TAG_PHOTO_REF.child("\(thumbnail)").downloadURL { (thumbnailUrl, error) in
if error != nil {
print(error?.localizedDescription as Any)
} else {
thumb = thumbnailUrl
}
}
return thumb
}
cell.photo.kf.setImage(with: downloadThumbnail(thumbnail: selectedTag.thumbnail))
When I run this code I got
fatal error: unexpectedly found nil while unwrapping an Optional value
with return thumb line.
But if I run only print(thumbnailUrl) instead of return, it prints correct thumbnail url. Can anyone know why I got this error?
Thanks.
You can not guarantee that thumb will never be nil. Because of this, you should not be using !. Because you have no control over it and have not set it manually, you need to make it an optional.
var thumb: URL?
Secondly, you have an internet call. You are returning thumb before you get a response from that call, because of that, thumb is nil, but you told us with the ! that that is impossible, so you crash.
If you put in breakpoints, you should notice that you will hit return thumb on your method before you hit the if error != nil line. You can't use a return for this, because the method will always return before it gets a response from firebase, so your URL will always be nil. I would instead send a URL in a completion.
I haven't checked the firebase code, but if all is right with it, this is the order you want.
So:
func downloadThumbnail(thumbnail: String,withCompletion comp: #escaping (URL?, Error?) -> ()) {
let _ = DataService.dataService.TAG_PHOTO_REF.child("\(thumbnail)").downloadURL { (thumbnailUrl, error) in
if error != nil {
print(error?.localizedDescription as Any)
comp(nil, error)
} else {
comp(thumbnailUrl, nil)
}
}
}
So when you call it somewhere else:
func getMyImage(cell: UITableViewCell) {
downloadThumbnail(thumbnail: selectedTag.thumbnail) { (thumbnailUrl, error) in
if error != nil {
//show some sort of alert for the user here? or do something to handle the error?
} else {
//the url is an optional URL, so check to make sure it isn't nil
if let url = thumbnailUrl {
cell.photo.kf.setImage(with: url)
} else {
//you didn't get an error from your firebase response
//but the thumbnail url it gave you is broken for some reason
//so again, do something about your error here
}
}
}
If this doesn't match the design pattern of your app, let me know. I assumed you were using a tableview and that these methods might be in different classes.
I'm converting below code to Swift 3.
if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error:nil) {
// 2.
context.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics,
localizedReason: "Logging in with Touch ID",
reply: { (success : Bool, error : NSError? ) -> Void in
// 3.
dispatch_async(dispatch_get_main_queue(), {
if success {
self.performSegueWithIdentifier("dismissLogin", sender: self)
}
if error != nil {
var message : NSString
var showAlert : Bool
// 4.
switch(error!.code) {
Step 4 does not work anymore on Xcode 8, Swift 3. So I could not do the following cases:
switch(error!.code) {
case LAError.AuthenticationFailed.rawValue:
message = "There was a problem verifying your identity."
showAlert = true
break;
Currently, it's seems there was no solution that I could find yet. Any suggestion, please let me know.
Thanks a lot!
First change your reply closure of evaluatePolicy method, in Swift 3 it is Error not NSError.
reply: { (success : Bool, error : Error? ) -> Void in
Second, change performSegue with identifier like this.
performSegue(withIdentifier: "dismissLogin", sender: self)
In Swift 3 you need to convert Error object to NSError or use _code with Error instance instead of code.
switch((error! as NSError).code)
OR
switch(error!._code)
You need to also change you dispatch syntax like this.
Dispatch.async.main {
//write code
}
This actually got a lot easier
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
localizedReason: "Logging in with Touch ID",
reply: { (success : Bool, error : Error? ) -> Void in
// 3.
DispatchQueue.main.async {
if success {
self.performSegueWithIdentifier("dismissLogin", sender: self)
}
if let error = error {
var message : NSString
var showAlert : Bool
// 4.
switch error {
case LAError.userCancel:
//do stuff
This is mostly from memory, but I think it is correct.
Prior to downloading Xcode 8 I was able to perform functions from the Particle iOS Cloud SDK (Spark SDK) without any problem. Now, I am being given multiple errors all similar to the ones below.
SparkCloud.sharedInstance().loginWithUser(username!, password: password!) { (error:NSError?) -> Void in
// Deactivates activity indicator.
activityIndicator.stopAnimating()
// Reallows interaction events.
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if error != nil {
Utils.showAlertOnVC(self, title: "Invalid parameters.", message: "Please try again.")
self.clearText()
} else {
self.performSegueWithIdentifier("loginUser", sender: self)
}
}
Error: Cannot convert value of type '(NSError?) -> Void' to expected argument type 'SparkCompletionBlock?'
SparkCloud.sharedInstance().getDevices { (sparkDevices: [AnyObject]?, error: NSError?) -> Void in
if let sparkDevices = sparkDevices as? [SparkDevice] {
for device in sparkDevices {
self.myPhotons.append(device)
self.tableView.reloadData()
}
}
}
Error: Cannot convert value of type '([AnyObject]?, NSError?) -> Void' to expected argument type '(([Any]?, Error?) -> Void)?'
I've tried updating my Podfile and toying with the function calls but nothing seems to work. I'm wondering if it has something to do with the updates in Swift 3.0 but I can't find anything that would indicate so. Any help with this issue would be much appreciated.
Instead of NSError, use Error:
SparkCloud.sharedInstance().getDevices { (sparkDevices: [AnyObject]?, error: Error?)
This did the trick for me.
The Code below returns an error:
Cannot Covert value of type '(PDUser!, NSError!) -> Void' to expected argument type 'PFUserResultBlock'
PFAnonymousUtils.logIn{ (user: PFUser?, error: NSError?) -> Void in
if let user = user {
if user != nil {
println("Success")
}
} else {
println("Failed")
}
}
I looked at a few examples below for reference to see if there was a solution:
(1)Parse Facebook logInInBackgroundWithReadPermissions
(2)PFFacebookUtils login background cannot convert value to PFUserResultBlock
(3) iOS Developers Guide
The type inference is being thrown off. Try without the types. So PFAnonymousUtils.logIn{ (user, error) in This might fix it.
So With some help here's a complete solution:
Taking a suggestion where I would have to place :
PFAnonymousUtils.logIn{ (user, error) in
over
PFAnonymousUtils.logIn{ (user: PFUser?, error: NSError?) -> Void
the next error would be this line:
if let user = user {
where the compiler assumes that this isn't an optional, so the final solution in code would be
PFAnonymousUtils.logIn{ (user, error) in
if error == nil {
print("Success")
}
else {
print("Failed")
}
}
This way, it checks for an error, if there is an error, the code will print a line indicating as such.
I've been delving into swift and using the Parse SDK and was wondering if anyone could shed some light on the following:
I am trying to delete an object in the Parse DB, and have set the method up to fail - but it fails to fail.
func destroy(onComplete: Bool -> Void) {
let object = PFObject(className: "ClassName")
object.deleteInBackgroundWithBlock({
(success: Bool, error: NSError?) -> Void in
NSLog("Error: \(error)")
if let error = error {
onComplete(false)
NSLog("Error: \(error)")
} else {
onComplete(success)
}
})
}
When I set the objectId property the object is destroyed fine, but here I am omitting it so, obviously, nothing is destroyed, but when the closure runs, success is always equal to true, and error is always nil.
Does anyone know if this is intended behaviour, because if no object is destroyed, surely, either success should equal false, or error should be non-nil?
Thanks
Paul