Swift: Corelocation handling NSError in didFailWithError
Update for Swift 4: The error is now passed to the callback as error: Error
which can be cast to an CLError
:
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
if let clErr = error as? CLError {
switch clErr {
case CLError.locationUnknown:
print("location unknown")
case CLError.denied:
print("denied")
default:
print("other Core Location error")
}
} else {
print("other error:", error.localizedDescription)
}
}
Older answer: The Core Location error codes are defined as
enum CLError : Int {
case LocationUnknown // location is currently unknown, but CL will keep trying
case Denied // Access to location or ranging has been denied by the user
// ...
}
and to compare the enumeration value with the integer err.code
, toRaw()
can be used:
if err.code == CLError.LocationUnknown.toRaw() { ...
Alternatively, you can create a CLError
from the error code and check that
for the possible values:
if let clErr = CLError.fromRaw(err.code) {
switch clErr {
case .LocationUnknown:
println("location unknown")
case .Denied:
println("denied")
default:
println("unknown Core Location error")
}
} else {
println("other error")
}
UPDATE: In Xcode 6.1 beta 2, the fromRaw()
and toRaw()
methods have been
replaced by an init?(rawValue:)
initializer and a rawValue
property, respectively:
if err.code == CLError.LocationUnknown.rawValue { ... }
if let clErr = CLError(rawValue: code) { ... }
Problems with CoreLocation
Have you added the NSLocationWhenInUseUsageDescription
key to your plist? - The value should be a string describing why you want to use the users location.
<key>NSLocationWhenInUseUsageDescription</key>
<string>Required to provide information about your location.</string>
If its all working correctly the didUpdateLocations
delegate method should return an array of locations, you can print these out like so...
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for loc in locations {
print(loc)
}
}
If you want to continually monitor the location you can call manager.startUpdatingLocation()
instead of manager.requestLocation()
Error handling didStartUpdatingLocation
Once check Error Types like this , i wrote in Obj-c but ur question is in Swift
- (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error
{
switch([error code])
{
case kCLErrorNetwork:
{
@"Network Error message:@"Please check your network connection.";
}
break;
case kCLErrorDenied:{
@"Enable Location Service message:@"You have to enable the Location Service to use this App. To enable, please go to Settings⚙->Privacy->Location Services";
}
break;
default:
{
}
break;
}
}
Error handling didStartUpdatingLocation
Once check Error Types like this , i wrote in Obj-c but ur question is in Swift
- (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error
{
switch([error code])
{
case kCLErrorNetwork:
{
@"Network Error message:@"Please check your network connection.";
}
break;
case kCLErrorDenied:{
@"Enable Location Service message:@"You have to enable the Location Service to use this App. To enable, please go to Settings⚙->Privacy->Location Services";
}
break;
default:
{
}
break;
}
}
Why SKProductsRequestDelegate/SKRequestDelegate didFailWithError throws EXC_BAD_ACCESS on NSError?
I finally found the reason. It is not related to SKProductsRequest
!
I think there is a nasty bug with NSLog
and string interpolation because when I replace:
NSLog("Failed: \(error.debugDescription)")
by
print("Failed: \(error.debugDescription)")
all is fine!
Apparently, the content of the error message can provoke a EXC_BAD_ADDRESS in NSLog (even without string interpolation in fact: NSLog(error.debugDescription)
fails too).
Related anwser: https://stackoverflow.com/a/29631505/249742
NSLog("%@", error.debugDescription)
seems to work fine in every cases.
Perhaps NSLog(variable)
is a misuse of NSLog, but I think NSLog(\(variable))
should be interpreted like NSLog("%@", variable)
. Else, there is no reliable way to interpolate strings with NSLog using the swift way \()
.
Can't Determine When User Doesn't Allow Location Services
the
didFailWithError
ordidChangeAuthorizationStatus
methods are not being called
Those are delegate methods. Your location manager does not have any delegate - certainly it does not have you (the AwesomeViewController instance) as a delegate. So it is not going to call those methods, ever. You need to set the location manager's delegate (in this case you would set it to self
).
iOS Domain=kCLErrorDomain Code=1 before ask for location permission
Do you mean CLAuthorizationStatus? https://developer.apple.com/documentation/corelocation/clauthorizationstatus
let status: CLAuthorizationStatus = CLLocationManager.authorizationStatus
if status == .notDetermined {
// Ask permissions
}
Related Topics
Swift Http Request Use Urlsession
Compare Textfield.Text to Firebase String Swift
Default Argument Not Permitted in a Tuple Type When Defining Function Type
Nsurl Found Nil While Unwraping an Optional Value
How to Cast Any to an Optional
Format Realtime Stopwatch Timer to the Hundredth Using Swift
Function Throws and Returns Optional.. Possible to Conditionally Unwrap in One Line
Transform a Swift Sequence in to Adjacent Pairs
Expandable Sections Uitableview Indexpath Swift
How to Create an Array of Functions
Make Int Round Off to Nearest Value
Converting Swift Array to Cfarray in Xcode 8 (Swift 3)
Unsaferawpointer Assumingmemorybound VS. Bindmemory
How to Filter Characters from a String in Swift 4
How to Get Start and End of the Week in Swift
Can't Understand How Collision Bit Mask Works