Brian Coleman

  • Home
  • ABOUT
  • SERVICES
  • PORTFOLIO
  • BLOG
  • Contact

July 2014 20

Play LED Baseball

About a year ago I competed in the first Rogers Digital Media Hackathon, and I won with my game LED Baseball. You can read about it in My First Hackathon. It’s been a very busy year since I worked on it, but over the last couple of weeks I took the time to finish it and release it to the App Store. As of today it’s live in the store! To complete it I added support for iPhone4, iPhone5 and iPad. It took awhile to resize all the graphics to fit the different screens, and I wasn’t sure how well it would work on a phone since it was originally developed for a tablet, but I’m rather pleased with how it turned out.

Pitch, hit and run the bases with the only electronic baseball game for your iPhone, iPod Touch and iPad.

Computer pitches curves or fastball’s! Swing away! Run the bases. Home Run!

Beat the computer or a friend! Hit a homer!

The speed and excitement of real baseball.
It’s you against a built-in thinking computer.
A challenge for fans of all ages.
A whole new kind of fun.

• 5-Innings of Baseball
• Computerized Scoring
• Computer controls pitching and plays defence
• You control hitting and base running
• Play Two-Players Against a Friend
• Full Electronic Sounds Included
• You swing away at a fast one, hit a curve, stretch a single, even hit a home run!

Plenty of excitement awaits you, so PLAY BALL!!


led_app_store

1

2

3

4

5

led_app_store

July 11, 2014 My Appsapps, games

Tutorial: Calculate Age in Swift

For a new application I’m working on I needed to capture the birth date of a user and validate if they are old enough to use the app.

Below is a simple method in Swift to return the age of a user after passing in the users birthday.

func calculateAge (birthday: NSDate) -> NSInteger {
    
    var userAge : NSInteger = 0
    var calendar : NSCalendar = NSCalendar.currentCalendar()
    var unitFlags : NSCalendarUnit = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay
    var dateComponentNow : NSDateComponents = calendar.components(unitFlags, fromDate: NSDate.date())
    var dateComponentBirth : NSDateComponents = calendar.components(unitFlags, fromDate: birthday)
    
    if ( (dateComponentNow.month < dateComponentBirth.month) ||
        ((dateComponentNow.month == dateComponentBirth.month) && (dateComponentNow.day < dateComponentBirth.day))
        )
    {
        return dateComponentNow.year - dateComponentBirth.year - 1
    }
    else {
        return dateComponentNow.year - dateComponentBirth.year
    }
}

To call the method and print out the return value in the console.

println("User Age: \(calculateAge(self.datePicker.date))")
July 10, 2014 Swift, Tutorialsios8, swift, tutorial

Tutorial: Post to Web Server API in Swift using NSURLConnection

In the past I have always used the ASIHTTPRequest third-party library to make an asynchronous request to a server. It’s been outdated for at least a year but still worked for all I needed it for. I thought I’d look for a more native approach to use in Swift instead of using a Bridging Header to import the library. Below is a simple and effective way to connect to a web API (Perl, PHP, Rails) from Swift using NSURLConnection.

Communicating to the API From Your App

let url = NSURL(string:"")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"

// set Content-Type in HTTP header
let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)

// set data
var dataString = ""
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData

// set content length
//NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request)

var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)

let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
println("API Response: \(results)")
  1. Replace with the URL to your script, i.e. http://www.brianjcoleman.com/scripts/login.php
  2. Replace with the attributes you want to post to the script, i.e. ACTION=SAVE&NAME=Brian&EMAIL=test@brianjcoleman.com
  3. If you are to retrieve data from the server for confirmation or you’re pulling data from the server you’ll receive that in the “results” variable

Most of the top apps in the App Store communicate with a server for one reason or another. An app may need to send user data such as game scores or currency to a global database to track rankings or currency. It may serve up dynamic content or even ads that the owner wishes to change without making an app update. All of this and more require an API (application programming interface) to communicate between the app and the web server.

Setup the PHP Web API

To start you’ll need a web server that will host the PHP script. One of the best shared hosts in the US is 1 & 1. You can host as many URLs and MySQL databases as you wish for around $100 a year. Next you need to write your PHP script that will be sending data to your app.

The code below is PHP, you can cut and paste it into a text editor and save it as adAPI.php, then upload it to your server. Be sure to set the permissions of the file on the server to 0755 to make it executable. You can do that using any FTP program and right clicking on the file and selecting “Permissions”. If they are not set correctly the app will not be able to execute the PHP script on the server and it will return an error.

id = $id;
$this->image_url = $image_url;
$this->url = $url;
}
}

$myAd = new Ad(1, "image_url", "url");
echo json_encode($myAd);
?>
July 8, 2014 Swift, Tutorialsapi, ios8, swift, tutorial

Tutorial: Facebook Login in Swift using a Bridging Header

Note: Newer tutorial available. If you would like to learn how to implement Facebook Login using Facebook SDK 4.0 using Swift, read Tutorial: How To Use Login in Facebook SDK 4.0 for Swift

If you are building a new game for iOS one of the key features you are going to need is a way to capture user information to populate their profile and for Facebook Leaderboards so users can compete against their friends.

As we are all getting up to speed with Swift, I’ve been working on a couple new games and I came across a few issues when trying to incorporate existing frameworks into my project, like the Facebook SDK.

Below is a tutorial to help you add the existing Facebook SDK into your Swift project. This will be useful until Facebook releases an update to their SDK that supports Swift.

Setting up the Facebook SDK in Your Swift App

  1. Visit the Getting Started with the Facebook iOS SDK documentation to download the Facebook SDK and install it.
  2. Add the FacebookSDK.Framework to your project as you normally would. Drag it or add it using the “Linked Frameworks and Libraries” within your target settings.
  3. You won’t be able to use the normal #import <FacebookSDK/FacebookSDK.h> to link the framework so you need to do a work around by creating a Bridging Header.
  4. Create a new “Objective-C” Header file by clicking “File > New”
    Screen Shot 2014-07-07 at 9.18.23 AM
    Screen Shot 2014-07-07 at 9.18.42 AM
  5. All you need in the Bridging-Header.h is the import statement for the Facebook SDK.
    //
    // Bridging-Header.h
    // SwiftBook
    #import 
    
  6. Next you need to add it to your target’s build settings:In Xcode, if you go into the build settings for your target, and scroll all the way down you’ll find a “Swift Compiler – Code Generation” section.

    Set “Objective-C Bridging Header” to <#PROJECT_NAME>/Bridging-Header.h

    “Install Objective-C Compatibility Header”, should be set to “Yes”.

    Here’s what it looks like:
    Screen Shot 2014-07-28 at 9.52.11 AM

  7. Now your app should be able to access all of the APIs in the Facebook SDK.
  8. Now we’ll setup our app to use Facebook Login.
  9. Add the following to your AppDelegate.swift. The “OpenURL” method allows your app to open again after the user has validated their login credentials.
    //
    // AppDelegate.swift
    // SwiftBook
    //
    // Created by Brian Coleman on 2014-07-07.
    // Copyright (c) 2014 Brian Coleman. All rights reserved.
    //import UIKit
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    // Override point for customization after application launch.
    
    FBLoginView.self
    FBProfilePictureView.self
    
    return true
    }
    
    func application(application: UIApplication, openURL url: NSURL, sourceApplication: NSString?, annotation: AnyObject) -> Bool {
    var wasHandled:Bool = FBAppCall.handleOpenURL(url, sourceApplication: sourceApplication)
    return wasHandled
    }
    
    func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }
    
    func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }
    
    func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }
    
    func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }
    
    func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    }
    
  10. Add the FBLoginViewDelegate methods to your ViewController.swift.
    //
    // ViewController.swift
    // SwiftBook
    //
    // Created by Brian Coleman on 2014-07-07.
    // Copyright (c) 2014 Brian Coleman. All rights reserved.
    //import UIKit
    
    import UIKit
    
    class ViewController: UIViewController, FBLoginViewDelegate {
    
    @IBOutlet var fbLoginView : FBLoginView!
    
    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    
    self.fbLoginView.delegate = self
    self.fbLoginView.readPermissions = ["public_profile", "email", "user_friends"]
    
    }
    
    // Facebook Delegate Methods
    
    func loginViewShowingLoggedInUser(loginView : FBLoginView!) {
    println("User Logged In")
    }
    
    func loginViewFetchedUserInfo(loginView : FBLoginView!, user: FBGraphUser) {
    println("User: \(user)")
    println("User ID: \(user.objectID)")
    println("User Name: \(user.name)")
    var userEmail = user.objectForKey("email") as String
    println("User Email: \(userEmail)")
    }
    
    func loginViewShowingLoggedOutUser(loginView : FBLoginView!) {
    println("User Logged Out")
    }
    
    func loginView(loginView : FBLoginView!, handleError:NSError) {
    println("Error: \(handleError.localizedDescription)")
    }
    
    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }
    
    }
    

    Notice that I have used the exactly same FBLoginViewDelegate methods as used in Objective-C but reformatted the method calls to support the new Swift syntax.

    Here’s an example:

    - (void)loginViewFetchedUserInfo:(FBLoginView *)loginView user: (id)user;
    
    • The method name starts with “loginViewFetchedUserInfo”. That stays the same.
    • The parameter is a pointer of type “FBLoginView” This will get translated to an optional of type FBLoginView because it can be nil. The convention is to make it an Implicitly Unwrapped Optional so it will become FBLoginView!
    • Protocols are types in and of themselves in Swift, so the user parameter will become simply FBGraphUser.
    • The first parameter in a swift method is assumed to be just an internal name so the parameter can be named anything but for consistency we will name it the same: “loginView”
    • The second parameter in a swift method is assumed to be both internal and external. In the Objective-C version they happen to be the same so we can simply use it once and Swift will make it both the internal and external name

    This leaves us with this translation:

    func loginViewFetchedUserInto(loginView : FBLoginView!, user: FBGraphUser)
    
  11. Add a UIView to your Storyboard and hookup the outlet of the view to fbLoginView.
    Screen Shot 2014-07-07 at 9.41.07 AM
  12. There is one final step needed to be performed, and that is to add three new keys to the project’s .plist file. So, open it by clicking on the Supporting Files group in the Project Navigator and then on the Info.plist file. Add a new key named FacebookAppID, and as its value paste the App ID value which you can copy from the Facebook dashboard, at the top of it. Similarly, add the FacebookDisplayName key, and in its value paste the Display Name.Finally, create a new key named URL Types, and set its type to array with one item only. Give it the URL Schemes title and make it an array too. In the one and only item that should be contained, set the app ID value you copied from the Facebook dashboard, prefixing it with the fb literal. The image below shows all the three additions on the .plist file:
    Screen Shot 2014-07-07 at 10.01.50 AM
  13. Compile your project and you should see the following screen. Once you click the “Log in with Facebook” button, it should kick you out to the Facebook App or the Facebook website for the user to login. After they have, it’ll kick back to your app and you’ll see the user information in the console.
    Screen Shot 2014-07-07 at 10.00.33 AMNow it’s up to you to use the users information as you wish. Maybe to populate a user profile or to pull the users Facebook friends so you can build a leaderboard.

    You can grab the full source code for this tutorial. Note: Updated for XCode6-Beta4.

    I hope this helped you get through a couple hurdles with integrating Facebook Login in Swift. If you run into some errors and you think everything should be fine, try Cleaning the project “Product > Clean” or restart your project file. Xcode 6 is currently in beta, and I’ve had a lot of issues with it so far. Hopefully Apple will release an update soon that fixes some of the initial bugs with the compiler.

July 7, 2014 Swift, Tutorialsfacebook, swift, tutorial

Video: Closures II

Global and nested functions, as introduced in Functions, are actually special cases of closures. Closures take one of three forms:

  • Global functions are closures that have a name and do not capture any values.
  • Nested functions are closures that have a name and can capture values from their enclosing function.
  • Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context.

Swift’s closure expressions have a clean, clear style, with optimizations that encourage brief, clutter-free syntax in common scenarios. These optimizations include:

  • Inferring parameter and return value types from context
  • Implicit returns from single-expression closures
  • Shorthand argument names
  • Trailing closure syntax

This video was developed by Skip Wilson. You can follow him on Twitter (@SkipAllMighty).

July 5, 2014 Videosswift, tutorial, video
Page 2 of 4«1234»
Recent Posts
  • Classix for iPhone, iPad & Apple TV
  • Tutorial: How to test your app for IPv6 compatibility
  • Tutorial: Testing SSL using Charles Proxy on an iOS Device
  • Tutorial: 3D Touch – Quick Actions in Swift
  • tvOS Tutorial: Top Shelf in Swift
Featured Apps
Classix
Sportsnet
TAGS
tutorialswiftios8iosobjective-cvideogamesstrategynewsframeworkappsmonitizefacebookwatchappleios7toolstvosios9apiprovisionsocialtutorialsbooksdesignbookiapIPv6iTunes Connect
Search
TAGS
tutorialswiftios8iosobjective-cvideogamesstrategynewsframeworkappsmonitizefacebookwatchappleios7toolstvosios9apiprovisionsocialtutorialsbooksdesignbookiapIPv6iTunes Connect
ABOUT
Brian is a Lead iOS/tvOS Developer from Toronto with over 18 years of multifaceted experience including development, design, business analysis and project management.

FOLLOW ME
    
Email Subscription
Sign up for my newsletter to receive the latest news and tutorials posted.

Enter your email address:

2023 © Brian Coleman