Tsuharesu
Tsuharesu

Reputation: 1169

Testing for UIApplicationOpenSettingsURLString existence with Swift

On iOS 8 Apple gave us the possibility to go to the App Settings right from our app, using the Constant UIApplicationOpenSettingsURLString

UIApplication.sharedApplication().openURL(NSURL.URLWithString(UIApplicationOpenSettingsURLString))

There's a code to test if this Constant exists on iOS 7, but it uses ObjC and pointes. Apple did this on their code: https://developer.apple.com/library/ios/samplecode/AppPrefs/Listings/RootViewController_m.html

How can I make something like this using Swift?

Upvotes: 12

Views: 11129

Answers (3)

Adam Tegen
Adam Tegen

Reputation: 25887

You could use #available:

if #available(iOS 8.0, *) {
    UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!);
} else {
    // Fallback on earlier versions
};

Upvotes: 1

Keller
Keller

Reputation: 17081

In Swift:

switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) {
  case .OrderedSame, .OrderedDescending:
    UIApplication.sharedApplication().openURL(NSURL.URLWithString(UIApplicationOpenSettingsURLString))
  case .OrderedAscending:
    //Do Nothing.
}

In Objective-C:

if (&UIApplicationOpenSettingsURLString != NULL) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}

Upvotes: 22

Tsuharesu
Tsuharesu

Reputation: 1169

It's not the same as checking for a Constant, but if you know the API version that contains the Constant (in my case, iOS 8), there are some techniques: http://nshipster.com/swift-system-version-checking/

One of them is:

switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) {
case .OrderedSame, .OrderedDescending:
    println("iOS >= 8.0")
case .OrderedAscending:
    println("iOS < 8.0")
}

Upvotes: 1

Related Questions