Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 395
Reinhard Männer Avatar asked Sep 15 '16 14:09

Reinhard Männer


1 Answers

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

like image 145
ccjensen Avatar answered Oct 19 '22 03:10

ccjensen