Benja0906 Benja0906 - 2 months ago 13
Objective-C Question

How to convert Objective-C code to Swift code - errorhandling ,iOS

I'm trying to convert this text to swift:

- (void)sendData:(NSData*)data
{
NSError *error;
GameKitHelper *gameKitHelper = [GameKitHelper sharedGameKitHelper];

BOOL success = [gameKitHelper.match
sendDataToAllPlayers:data
withDataMode:GKMatchSendDataReliable
error:&error];

if (!success) {
NSLog(@"Error sending data:%@", error.localizedDescription);
[self matchEnded];
}
}


Now I've gotten so far here:

func sendData(data: NSData) {
var error: NSError?
var gameKitHelper = GameKitHelper.sharedGameKitHelper()
var success = try! gameKitHelper.match.sendDataToAllPlayers(data, withDataMode: GKMatchSendDataReliable)
if !success {
print("Error sending data:\(error.localizedDescription)")
self.matchEnded()
}
}


But It's giving me an error at
if (!succes)
and I read on apples documentation that the objective-c version of
.sendDataToAllPlayers()
will return a bool but the swift version won't.

Apple Documentation - GKMatch

So how can I handle the error

Answer

The sendDataToAllPlayers function throws an exception if an error occurs. You need a catch block to handle it:

func sendData(data: NSData) {
    var gameKitHelper = GameKitHelper.sharedGameKitHelper()
    do {
        try gameKitHelper.match.sendDataToAllPlayers(data, withDataMode: .Reliable)
    }
    catch let error as NSError {
        print("Error sending data:\(error.localizedDescription)")
        self.matchEnded()
    }

}