WCSessionDelegate: sessionDidBecomeInactive and sessionDidDeactivate have been marked unavailable, but are required
Asked Answered
S

1

13

I just converted a Swift 2 app to Swift 3, using the convert function of Xcode 8.

My code has a class marked as WCSessionDelegate.

In Swift 2 it compiled without the methods sessionDidBecomeInactive and sessionDidDeactivate.

If I compile the Swift 3 version, the compiler complains that my class does not conform to protocol WCSessionDelegate, which is apparently correct.
It then offers to insert stubs for both functions:

public func sessionDidBecomeInactive(_ session: WCSession) { }  
public func sessionDidDeactivate(_ session: WCSession) { }

After these stubs are inserted, these errors are reported:

Cannot override 'sessionDidBecomeInactive' which has been marked unavailable  
Cannot override 'sessionDidDeactivate' which has been marked unavailable  

How can I fix this problem?

Shirr answered 15/9, 2016 at 14:17 Comment(3)
The class where you added the deactivate and inactive callbacks; is it compiled and used for both the iOS app and WatchKit extension?Mohamedmohammad
@ccjensen: Yes, this class is shared.Jethro
@ccjensen: The problem exists also, if the class has only the watch extension as target.Jethro
M
49

Because the delegate methods sessionDidDeactivate and sessionDidBecomeInactive are marked as unavailable on watchOS you will have to make the compiler ignore those pieces of code in the shared class. You can do so using the following preprocessor macro:

#if os(iOS)
public func sessionDidBecomeInactive(_ session: WCSession) { }  
public func sessionDidDeactivate(_ session: WCSession) {
    session.activate()
}
#endif

Please also note I added the activate call in the sessionDidDeactivate call. This is to re-activate the session on the phone when the user has switched from one paired watch to second paired one. Calling it like this assumes that you have no other threads/part of your code that needs to be given time before the switch occurs. For more information on supporting the quick watch switching you should take a look at the Apple sample code

Mohamedmohammad answered 19/9, 2016 at 16:53 Comment(2)
Thanks for your efforts, but the suggested code improvements did not eliminate the compiler errors, see me edit above.Jethro
"Function-like macro 'os' is not defined"Ancohuma

© 2022 - 2024 — McMap. All rights reserved.