Search code examples
watchkitswift3xcode8wcsession

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


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?


Solution

  • 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