Info

Programmer by day, artist by night

Posts tagged Swift

The Animation assignment also referred to as the Breakout game is the 5th and final assignment from the CS193P course Developing iOS 8 Apps with Swift from Stanford University. Really happy to have finally finished this assignment. In my opinion this was the most complex of all the five assignments in this course.

Platform: iOS 9
Swift: 2.1

Full source code available here at the Github repository

All the 9 required tasks mentioned in page 2 of the specifications document were completed. Though device rotation is not mentioned as a requirement it does appear as a hint. I didn’t allow device rotation because it seemed to me that it would drastically affect the game play negatively.

The main challenge that I faced in completing this assignment was the nuance of using UIKit Dynamics to make a game. There were numerous issues that I was not fully clear in the beginning on how to implement them. So slowly chipped away each issue one by one before I had a clear picture of how they all fit together.

I am summarizing some of the main issues I had problems with below and how I solved them. Please see the inline documentation in the source code for all the issues and their implementation details.

  1. Creating the ball and animating it: The shape of the rectangular view of the ball as the collision boundary didn’t seem right. Though prior to iOS 9 I don’t think it was possible to do anything about it. Please see Variation on Dropit Demo from Lecture 12 on how I solved this by setting UIDynamicItemCollisionBoundsType to be an .Ellipse.
  2. Animating the paddle on pan gesture and having the ball collide. Hints are given in the assignment specifications on how to implement this, but since I hadn’t done it before it wasn’t clear what the outcome would look like.
    The solution is to add the paddle as a subview of the game view and additionally create a bezier path that acts as a collision boundary in the UIDynamicBehavior subclass. Then update that boundary repeatedly whenever the paddle moves.
    Please see the movePaddle and syncPaddleBoundary methods for details.
  3. When the paddle was moved too quickly when hitting a ball, the ball would often end up trapped inside the paddle. The way I solved this is first check if the new paddle view’s frame intersected with the balls frame using CGRectIntersectsRect. If the frames don’t intersect then update / sync the boundary.
  4. Bricks are setup similar to the paddle, where they are added to the game view and their colliding boundaries added to the UIDynamicBehavior subclass.
    The ball collides with the boundary and when a collision is detected, the brick is removed from the game view. A bricks array [String:Brick] is used to track all the bricks in the game view and match them against the NSCopying identifier from the collision delegate.
    For details please see the methods createBricks and collisionBehavior.
  5. Special bricks and what behavior they would cause were open ended in the assignment specifications. I used 4 kinds of special bricks, one kind requires 3 hits before it disappears and the other three drops special powers that cause:
    • paddles to become larger
    • paddles to become smaller
    • adds additional balls
  6. Pausing the game when user taps on Settings. This wasn’t too hard to implement, the main issue here is the moving ball(s). I used an array to capture the balls and remove them from the screen. When user came back, I re-created them and added back their linear velocity. Please see method settingsDidUpdate.
  7. Instead of putting up an alert when the game ends, a view is used (where it’s state is toggled) to show that the game is over indicating if you won or lost. This view is also used during startup. The startGame and gameOver methods show how this is done.

The following extra credit tasks were also attempted:

  • Use sophisticated Dynamic Animation. For example, you might find a creative way to use the action method in a behavior or use something like linear velocity in your calculations.
  • As mentioned above, creativity will be rewarded, especially interesting game-play settings.
  • Do some cool artistic design in your user-interface (either by drawing or using images).
  • Pausing your game when you navigate away from it (to go to settings) is a bit of a challenge (because you basically have to freeze the ball where it is, but when you come back, you have to get the ball going with the same linear velocity it had). Give it a try. It’s all about controlling the linear velocity of the ball.

Video Demo

Usually it doesn’t make much sense to repeat code from a lecture demo, but for the Dropit project I think it’s worth to post an article based on a slight variation using the new features of UIKit Dynamics available in iOS 9.

This is perhaps a good time to mention that all the CS193P assignment solutions so far created has been based on Swift 2.1 and iOS 9, whereas the Stanford U. lectures and demos are based on Swift 1.2 and iOS 8.

The motivation to create the variation was a result of attempting to implement assignment 5. Particularly the ball which is a UIView and ideally should be round, even though UIViews are obviously rectangles. The good news is that iOS 9 provides a collisionBoundsType property which can be easily overridden in UIView:

class SphereView: UIView {
    // iOS 9 specific
    override var collisionBoundsType: UIDynamicItemCollisionBoundsType {
        return .Ellipse
    }
}

This sets the bounds of the view to be an ellipse and allows the right boundary collisions
as you might expect from a ball or sphere.

dropit-spaces-between-spheres dropit-no-spaces-between-spheres

The UIFieldBehavior new in iOS 9, also seems very interesting with properties like: dragField, springField, electricField, magneticField, noiseFieldWithSmoothness and more, which opens the door to new possibilities of animation in your apps. The Dropit variation also adds the noiseFieldWithSmoothness behavior for some cool
visual effects.

dropit-spheres-in-noise-field

With debugEnabled for UIDynamicAnimator (by adding a Swift bridging header *), you can see the noise field in action as it shifts by adding random noise. To enable UIView debugging, the following code needs to be added in the bridging header file:

@import UIKit;

@interface UIDynamicAnimator (AAPLDebugInterfaceOnly)

// Used in DropitViewController.swift file:
// lazilyCreatedDynamicAnimator.debugEnabled = true
@property (nonatomic, getter=isDebugEnabled) BOOL debugEnabled;
@end

Full source code of the demo is available here at Github:
https://github.com/sanjibahmad/Variation-on-Dropit-Demo

Video Demo

For more on what’s new in UIKit Dynamics in iOS 9, please see the WWDC 2015 video: What’s New in UIKit Dynamics and Visual Effects

* Please see this article on how to add the Swift bridging header: Adding a Swift Bridging Header

I have compiled the following resources based on my own experience and what I believe would be an effective learning path for beginners to get up to speed on iOS development.

1. Udacity

Start with the free iOS courses available at Udacity. They are not only fun and engaging but at the end will help you build 4 resume-worthy demos that you can showcase.

Additionally the following iOS specific free courses from Udacity are also recommended:

Time commitment: X months depending on your commitment

2. Ray Wenderlich

While taking the Udacity course, visit Ray Wenderlich http://www.raywenderlich.com/tutorials from time to time. Pick a topic or article that interests you and go through it.

The idea is, instead of going through everything available from A-Z, you pick something of interest and thoroughly explore it. Each article is on a particular topic and the time-investment is at most a few hours (in contrast to going through an entire book or course).

Time commitment: X hours depending on your commitment

The problem that I have experienced in learning any new technology is information retention. I found the above 2 techniques work well for me because:

  1. One path explores the area comprehensively with loads of relevant industry-specific projects, materials, demos, practice, quizzes, etc.
  2. Another path runs in parallel, diving deep into topics of personal interest for short sprints.

3. Stanford U.

Update, Jun 6, 2016: The latest course from Stanford U. “Developing iOS 9 Apps with Swift” can be found here: https://itunes.apple.com/us/course/developing-ios-9-apps-swift/id1104579961

Once the Udacity courses are done, take the Stanford U. course CS193P available for free on iTunes (https://itunes.apple.com/us/course/developing-ios-8-apps-swift/id961180099) for upping your game-level on iOS development. Some special highlights of the CS193P course that I found interesting were:

Using enums, structures, protocols, property observers, optional chaining, GCD, code re-use, OO design, MVC, autolayouts, iPhone/iPad compatibility, avoiding memory cycles, animations, internationalization, programming insights, well-designed assignments and much more. Using these in practice and specially in correct form as expected from a Stanford U. course, will definitely make you a better developer.

4. Additional Resources

Then further sharpen your axe, polish your skills and stay up-to-date with:

5. Algorithms

Useful for practicing algorithms in Swift for coding-tests/interviews. The sites below allow you to type the code solutions in Swift and run them online for evaluation.

6. Even More Resources

And here are even more resources added on request by the owners of the respective sites.
Enjoy 🙂

This is the 4th assignment from the course Developing iOS 8 Apps with Swift, Stanford University, CS193p, Winter 2015. There is one more assignment left in this course.

Platform: iOS 9, Swift: 2.1

Full source code available here at Github repository

Smashtag is a Twitter based app that allows users to:

  • perform Twitter search queries
  • view Tweet details (including images, links, users, hashtags)
  • save 100 most recent queries in a Recent tab
  • browse Tweet images in Colllection View

All the 10 Required Tasks were completed. In addition the following Extra Credit items were implemented:

  • In the Users section of your new UITableViewController, list not only users mentioned in the Tweet, but also the user who posted the Tweet in the first place.
  • When you click on a user in the Users section, search not only for Tweets that mention that user, but also for Tweets which were posted by that user.
  • Make the “most recent searches” table be editable (i.e. let the user swipe left to delete the ones they don’t like).
  • Add some UI which displays a new view controller showing a UICollectionView of the first image (or all the images if you want) in all the Tweets that match the search. When a user clicks on an image in this UICollectionView, segue to showing them the Tweet.
  • It would be cool to have “pinching” on the UICollectionView make the cell’s size get larger and smaller (i.e. showing more or fewer images).

Video Demo

CalculatorBrainThis project CalculatorBrain is a continuation of the previous project Calculator: Assignment 1, Stanford University Winter 2015 (iOS)

Source code available at Github

The ViewController code is now more lean and better organized since all calculation related logic has been moved to the model.

The project covers all the required tasks and most extra credit tasks.

In addition to the features listed in the previous project Calculator, this assignment provides:

  • A separate model for all calculations
  • Additional scientific functions
  • Memory functions
  • An Undo button (which previously functioned as the Backspace button)
  • Replaces the previous History function with a better implementation
  • Provides error messages

Two items were not implemented as described in the Extra Credit Hints section in the project specifications document:

  • The error messages come from the model with full error text instead of error codes for the ViewController to translate
  • Error handling is not implemented by associating any value (a function) with UnaryOperations and BinaryOperations

Video Demo:

calculator-assignment-1-stanford-university-ios-winter-2015Provides RPL (Reverse Polish Notation) calculator, where numbers are entered first then operations. For example, to add 6 and 4, you would:

6 Enter, 4 Enter, +
or 6 Enter, 4 +

This assignment solution covers all the required tasks including the ones listed under extra credit. Solution is Swift 2.0 and iOS 9.0 compatible.

Source code available at Github

Notes:

1. Overloaded the enter function for user input, because we want add to add it the history. The enter function is also called from other places in the code where we don’t want to add to history.

2. As mentioned in the assignment hints, floating point implementation was possible to add with a single-line of code:

if (digit != ".") || (digit == "." && display.text!.rangeOfString(".") == nil)

3. Pi implementation does not use the performOperation function but inline code since it’s easy to add:

case "π": displayValue = M_PI; enter()

Video Demo:

stanford-university-itunes-course-developing-ios-8-apps-with-swift
Stanford University has released a new course on iTunes a few days ago on developing iOS 8 apps with the Swift language:

https://itunes.apple.com/us/course/developing-ios-8-apps-swift/id961180099

So far lectures 1 to 5 has been released:

  1. Logistics, iOS 8 Overview
  2. More Xcode and Swift, MVC
  3. Applying MVC
  4. More Swift and Foundation Frameworks
  5. Objective-C Compatibility, Property List, Views

The high quality of the instructional material in this course follows in line with the previous iOS courses as taught by Paul Hegarty. Having followed the last iOS 7 course, suffice to say that these lectures provided by Stanford University for free are better than many paid online courses on iOS.

Paul Hegarty, who currently teaches at Stanford University used to work at NeXT Computers. Here’s a video of him talking about Steve Jobs.

Apple’s latest language Swift provides some nifty behaviors and characteristics. Three things we are loving about Swift so far are:

  1. Awesome OOP features: Structs, Enums, Classes can all have methods, optional binding, type safety
  2. Cool Functional language features: Closures (the shorthand syntax is a delight to use), nested functions and types
  3. Interesting Cocoa binding behaviors, as if the language was written to build beautiful Cocoa apps

We are getting solid feeling of how Swift was designed to create powerful and elegant programs. Experience will tell more down the line.

Here is a fun experiment with prefix operators. We wrote the following two custom global functions to mimic Lisp’s + prefix operator:

@prefix func + (ints: Int[]) -> Int {
    var sum = 0
    for int in ints {
        sum += int
    }
    return sum
}
@prefix func + (strings: String[]) -> String {
    var sum = ""
    for string in strings {
        sum += string
    }
    return sum
}

+[100, 200, 200]
// returns 500

+["comp", "uter"]
// returns "computer"