Whats the correct signature of receiveData:fromPeer:inSession:context: in swift?

223 Views Asked by At

im trying to rewrite my GameKit multiplayer game (local) in swift and have problems with some missing documentation for the language. I want to receive data from another peer so i set the dataReceiveHandler for my GKSession like this:

session.setDataReceiveHandler(self, withContext: nil)

in apples documentation it says that the dataReceiveHandler hast to implement a method with this signature:

SEL = -receiveData:fromPeer:inSession:context:

In the objective-c documentation is an example of how the signature should look like:

- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context;

if i try to rewrite this method in swift it looks like this:

func receiveData(data: NSData, fromPeer peer: String, inSession session: GKSession, withContext context: CMutableVoidPointer) {
    println("received data: \(data)")
}

and gives me this error when i receive a message:

Domain=com.apple.gamekit.GKSessionErrorDomain Code=30500 "Invalid parameter for -setDataReceiveHandler:withContext:" UserInfo=0x178462840 {NSLocalizedDescription=Invalid parameter for -setDataReceiveHandler:withContext:, NSLocalizedFailureReason=The handler does not respond to the correct selector.}

this means my method has not the correct signature. But what is the correct one?

3

There are 3 best solutions below

0
Sven Fridge On BEST ANSWER

Sorry that i have to edit this again but i have the actual answer now:

DONT USE GKSESSION! IT IS DEPRECATED SINCE iOS7!

Use:

MultipeerConnectivity.framework

1
Lukas On

You probably need to declare the types of the parameters as optionals (not sure whether this applies to the void pointer), i.e. func receiveData(data: NSData?, fromPeer peer: String?, inSession session: GKSession?, withContext context: CMutableVoidPointer) (you could also use ! instead of ? for implicitly unwrapped optionals).

Those parameters are pointers in Objective-C, i.e. they could be nil, which your current code cannot represent, thus it is does not have the correct signature. The way to represent possible nil values in Swift is to use optionals.

0
Bill On

It's a problem with renaming your parameters. You wrote withContext context instead of context withContext. The first name is the one that will be exposed to callers.

This should work:

func receiveData(data: NSData, fromPeer peer: String, inSession session: GKSession, context: CMutableVoidPointer) {
    println("received data: \(data)")
}