Saturday, July 18, 2015

Displaying Game Centre Leaders board from Swift

In last post, I showed how we can authenticate local player and how we can post score to default leader board.

In this post, I will show how we can display leader board using swift gamekit API. Below code shows how we can display GKGameCenterViewController. Game center viewcontroller needs delegate, which is called when view is dismissed. Also we need parent viewcontroller which will be used to display GKGameCenterViewController.
func showLeaderboard(viewController: UIViewController, 
    gameCenterDelegate: GKGameCenterControllerDelegate) {
    let gameCenterVC: GKGameCenterViewController = GKGameCenterViewController();
    gameCenterVC.leaderboardIdentifier = defaultLeaderBoard;
    gameCenterVC.gameCenterDelegate = gameCenterDelegate;
    viewController.presentViewController(gameCenterVC, animated: true, completion: nil);
Now we have code that can display leader board, but we need to make our class conform to GKGameCenterControllerDelegate protocol and implement required method. Below is code for delegate method. Which simply dismiss presented view controller.
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!) {
    gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
So, as you can see it's quite simple. Hope this will be helpful.

Saturday, July 11, 2015

Creating array of IBOutlets of NSLayoutConstraint's from Swift in iOS

While working on my iOS app, I wanted to modify UI Constraint set from Interface Builder from Swift code.

Below video shows how we can create Array of IBOutlets using Interface Builder. Here I am creating array of NSLayoutConstraint, which I want to modify from Swift Code.

Now lets see how we can manipulate constraints from swift. First we need to define array of IBOutlet. Below code shows the same.
@IBOutlet var constraints: Array?
Now, once you connect IBoutlet from Interface Builder as shown in above video. You can use those. In below code I am modifying NSLayoutConstraint's constant value.
if( Utils.isIPad() ) {
    for constraint: NSLayoutConstraint in constraints! {
        if(Utils.isIPad()) {
            constraint.constant = 30
That's it, Thank you for reading.

Monday, June 29, 2015

Posting score to Game Kit Leader board using swift

As you might already know, I recently started exploring Swift language and now I am trying out GameKit framework. While I have some experience in working with GameKit using Objective C. I wanted to do the same thing using swift. As such there are no API changes while using GameKit with Swift or Objective C. However there are some syntax change.

In this post, I will show how to Authenticate local player using GameKit framework and post score to LeaderBoard defined in iTune Connect Application setting.

Following is code snippet that shows how to Authenticate Local player. This function takes ViewController as argument. Login dialog will be displayed using this View controller. Rest will be taken care by GameKit framework.
func authenticateLocalPlayer(viewController: UIViewController) {
    let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()
    localPlayer.authenticateHandler = {(ViewController, error) -> Void in
        if((ViewController) != nil) {
            // 1 Show login if player is not logged in
            viewController.presentViewController(ViewController, animated: true, completion: nil)
        } else if (localPlayer.authenticated) {
            // 2 Player is already euthenticated & logged in, load game center
            self.isGameCenterEnabld = true                
        } else {
            // 3 Game center is not enabled on the users device
            self.isGameCenterEnabld = false
            println("Local player could not be authenticated, disabling game center")
Now we have authenticated local player. So when we are ready to post score to Leader Board. We can use below function. Here we are posting score to "defaultLeaderBoard". Which is identifier of Leader board defined in iTune connect App setting.

func submitScore( score: Int) {
    if( !isGameCenterEnabld ) {
    var sScore = GKScore(leaderboardIdentifier: defaultLeaderBoard)
    sScore.value = Int64(score)
    let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()
    GKScore.reportScores([sScore], withCompletionHandler: { (error: NSError!) -> Void in
        if error != nil {
        } else {
            println("Score submitted")
That's it. Hope this will be useful.

Sunday, June 28, 2015

Using NSNotificationCenter in Swift

NSNotificationCenter is a convenient method to implement Observer pattern in iOS, something similar to what we say Signal/Slot in Qt framework.

To register one self as observer to some event, you can use addObserver method form NSNotificationCenter. In below code you are adding self as observer, selector is method which will be called when event is triggered, name is name of event or notification in which we are interested in, and object is object from which we want to receive event from, nil means we are ready to receive event from any object.
    selector: "gameViewClosed", 
    name: "gameViewClosed", 
    object: nil);
Now to trigger the notification, you can use postNotificationName method from NSNotificationCenter. Following code shows the same. Here we are sending notification for "gameViewClosed" event, object nil mean deliver event to all interested objects.
    object: nil);
That's it, thanks for reading.

Friday, June 26, 2015

Playing sound using Swift

Posting small code snippet to that shows how to play sound using Swift in iOS.

First we need to import AVFoundation.
import AVFoundation
Then we need to create instance of AVAudioPlayer. I created a small utility function like below for the same.

private static func createAudioPlayer
( sound: String, type: String ) -> AVAudioPlayer {

    var error:NSError?;
    let soundUrl = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: type)!);
    var player = AVAudioPlayer(contentsOfURL: soundUrl, error: &error);
    return player;

And this function can be used like below.
public init() {
    // Removed deprecated use of AVAudioSessionDelegate protocol
    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil);
    AVAudioSession.sharedInstance().setActive(true, error: nil);
    correctAns = MusicHelper.createAudioPlayer("correctAns", type: "wav");
    wrongAns = MusicHelper.createAudioPlayer("wrongAns",type: "wav");
Now we can use AVAudioPlayer's play API to play the sound. Like below.

public func playCorrectAnsSound() {;

public func playWrongAnsSound() {;

That's it, thanks for reading.