Reputation:
What is equivalent of respond to selector for background tasks? I found the code in Objective-C. I'm trying to get the same in Swift.
Here is the Objective-C code:
if ([application respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)]){
bgTaskId = [application beginBackgroundTaskWithExpirationHandler:^{
})
Swift code:
if application.responds(to: #selector(self.beginBackgroundTaskWithExpirationHandler)) {
bgTaskId = application.beginBackgroundTask(expirationHandler: {() -> Void in
print("background task \(UInt(bgTaskId!)) expired")
})
It's saying BackgroundTaskManager has no member 'beginBackgroundTaskWithExpirationHandler'.
What is the exact thing we can replicate in Swift 3?
Upvotes: 0
Views: 444
Reputation: 318804
Unless you are attempting to support iOS 3 or earlier, there is no need to check for the existence of the selector since it was added in iOS 4.0.
But the Swift selector would be: beginBackgroundTask(expirationHandler:)
.
Here's a simple trick when trying to convert an Objective-C API into Swift. Pull up the API documentation in Xcode or online. Choose the Objective-C APIs. Find the method you wish to convert. Then switch the documentation to the Swift APIs. In a case like this you will now see the same method but in Swift.
Upvotes: 1