iosswiftmacossprite-kitcmmotionmanager

Declare property only on iOS


I am making a SpriteKit game for iOS, OSX, and tvOS. I am trying to use the accelerometer for my iOS target. I have the check for iOS on import of the CMMotionManager, but I can't seem to get the check to work when creating my motion manager property.

#if os(iOS)
    import CMMotionManager
#endif

class MainPlayScene: TCScene, SKPhysicsContactDelegate {

    //MARK: Properties
    //Motion
    @available(iOS 9, *) // Does not work, just trying things out....
    var motionManager:CMMotionManager {
        return motionManager
    }

How can I do this check?

EDIT: It is late here, and the more I think about it, correct me if I am on the wrong track all together. How can I use the accelerometer for iOS only and still share my scene code?


Solution

  • You use the same syntax that you used for your import statement. This is also what apple does in their sample game DemoBots.

    #if os(iOS)
    var motionManager....
    #endif
    
    #if os(tvOS)
    ...
    #endif
    

    You can also do multiple checks and use else/else if

     #if os(iOS) || os(tvOS)
     .... 
     #elseif os(OSX)
     ... 
     #endif
     ... // Code for other platforms
     #endif
    

    How to determine device type from Swift? (OS X or iOS)

    Just curious, any particular reason you make the motionManager property computed?