Being Swifty with Collection View and Table View Cells

Here’s a common scenario: You have a table view or collection view that has a variety of different types of content. You want to display varying cells based on these types of content, and they’re all mixed within a single section. Pardon the stand-in art, but it looks roughly like this:

In the Objective-C world, it was typical to just use an NSArray to hold whatever records your collection view was going to be using as a data source, and then for each element check what class it is before picking a cell. This case seems particularly not Swifty these days.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
    id record = self.records[indexPath.row];
    if([record isKindOfClass:[PlaythroughItem class]]) {
        // ...
    }
    else if([record isKindOfClass:[ReviewItem class]]) {
        // ...
    }
    else if([record isKindOfClass:[TrailerItem class]]) {
        // ...
    }
    return cell;
}

shudder

Okay so that’s not the most type-safe approach, although it’s surprisingly common in Obj-C iOS code. As a better alternative in Swift, we can use enum cases for the different item types, and perform lookups of the items themeselves as needed. Let’s look at an example.

Example

In an entertainment app I’m working on I’ve got a few types of cells for the types of news items that come in:

enum NewsItem {
  case Trailer(index: Int)
  case Review(index: Int)
  case Playthrough(index: Int)
}

The index is just a way to keep track of which item this it supposed to represent in the database. We take this approach to keep the amount of data needed to produce the collection view down. We don’t need all the associated data with every video to be present when putting together a collection view, we just need the info on what cell is tapped, after it is tapped.

Let’s say we have a simple collection view that shows one of these three and picks a custom cell for each. In a Swift file NewsFeed.swift I have that acts as the dataSource of my collection view for the main news view. Of particular interest is the cellForItemAtIndexPath method, which runs the NewsItem record through a switch and produces the correct type of cell, with the relevant information populated:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let record = records[indexPath.row]
    switch(record) {
    case .Playthrough(let index):
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PlaythroughCell", forIndexPath: indexPath) as! PlaythroughCollectionViewCell
        let playthrough = MediaDB.playthroughAtIndex(index)
        cell.titleLabel.text = playthrough.title
        cell.lengthLabel.text = playthrough.length.prettyTime
        return cell
    case .Review(let index):
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ReviewCell", forIndexPath: indexPath) as! ReviewCollectionViewCell
        let review = MediaDB.reviewAtIndex(index)
        cell.ratingLabel.text = "\(review.rating) out of 10"
        cell.titleLabel.text = review.title
        return cell
    case .Trailer(let index):
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("TrailerCell", forIndexPath: indexPath) as! TrailerCollectionViewCell
        let trailer = MediaDB.trailerAtIndex(index)
        cell.titleLabel.text = trailer.title
        cell.lengthLabel.text = trailer.length.prettyTime
        return cell
    }
}

This code works well enough, record is of type NewsItem which can be one of three cases for the different news items we support:

enum NewsItem {
  case Trailer(index: Int)
  case Review(index: Int)
  case Playthrough(index: Int)
}

The associated index value is so that we can find the individual item in the DB when the collection view wants to display a cell.

Something about this code didn’t sit right with me though. I felt that too much of the code was boilerplate; in particular the switch felt bulky and like it had too much work being done inside each case.

But what if I created a protocol for any data source that could be presented as a collection view cell? It would change on a view-by-view basis so I don’t actually want this in my model.. but I do like having it on these particular CollectionViewCell subclasses.

So, I created a protocol called NewsCellPresentable, which I can adhere to in extensions with my custom collection view cells:

protocol NewsCellPresentable {
    func configureForIndex(index: Int)
}
extension PlaythroughCollectionViewCell: NewsCellPresentable {
    func configureForIndex(index: Int) {
        let playthrough = MediaDB.playthroughAtIndex(index)
        self.titleLabel.text = playthrough.title
        self.lengthLabel.text = playthrough.length.prettyTime
    }
}
extension ReviewCollectionViewCell: NewsCellPresentable {
    func configureForIndex(index: Int) {
        let review = MediaDB.reviewAtIndex(index)
        self.titleLabel.text = review.title
        self.ratingLabel.text = "\(review.rating) out of 10"
    }
}
extension TrailerCollectionViewCell: NewsCellPresentable {
    func configureForIndex(index: Int) {
        let trailer = MediaDB.trailerAtIndex(index)
        self.titleLabel.text = trailer.title
        self.lengthLabel.text = trailer.length.prettyTime
    }
}

This feels much cleaner already. Now I can go back to my cellForItemAtIndexPath method and trim it down to just the following:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let record = records[indexPath.row]
    var cell: NewsCellPresentable
    switch(record) {
    case .Playthrough(let index):
        cell = collectionView.dequeueReusableCellWithReuseIdentifier("PlaythroughCell", forIndexPath: indexPath) as! PlaythroughCollectionViewCell
        cell.configureForIndex(index)
    case .Review(let index):
        cell = collectionView.dequeueReusableCellWithReuseIdentifier("ReviewCell", forIndexPath: indexPath) as! ReviewCollectionViewCell
        cell.configureForIndex(index)
    case .Trailer(let index):
        cell = collectionView.dequeueReusableCellWithReuseIdentifier("TrailerCell", forIndexPath: indexPath) as! TrailerCollectionViewCell
        cell.configureForIndex(index)
    }
    return (cell as! MediaCollectionViewCell)
}

What do you think? Is this a cleaner approach? Let me know if you have a different method in the comment, or let me know on Twitter. My username is @jquave.

P.S.

If you want to try this out yourself and don’t have the same DB layer as me… guess what? Neither do I! You can easily stub this out like this:

class MediaDB {
    class func titleForRecord(index: Int) -> String {
        return "Title!!"
    }
    class func trailerAtIndex(index: Int) -> Trailer {
        return Trailer()
    }
    class func reviewAtIndex(index: Int) -> Review {
        return Review()
    }
    class func playthroughAtIndex(index: Int) -> Playthrough {
        return Playthrough()
    }
}
struct Trailer {
    let title = "Trailer Title"
    let length = 190
}
struct Review {
    let title = "Review Title"
    let rating = 4
}
struct Playthrough {
    let title = "Playthrough Title"
    let length = 9365
}
enum NewsItem {
    case Trailer(index: Int)
    case Review(index: Int)
    case Playthrough(index: Int)
}

Personally I always stub things out with static values before I do the work of integrating with a backend service or whatever data provider is needed. This makes it much easier to iterate.


Sign up now and get a set of FREE video tutorials on writing iOS apps coming soon.



Subscribe via RSS

Open Source Swift – A Look At The Top Swift Repositories

Github, the most popular open source repository for open source software, offers a feature that let’s us view repositories by language. In this post, I want to dissect some of the most popular Swift repositories as of June 5th, 2015. So, let’s kick it off with the most starred Swift repository, Alamofire.

Alamofire

Alamofire is an “Elegant HTTP Networking in Swift”, written by Matt Thompson, a well known Objective-C developer responsible for the AFNetworking library. The library takes the built-in iOS networking features and abstracts them away in to a simpler, and more Swift-y API.

Take for example the case of a simple GET request that returns JSON:

Alamofire.request(.GET, "http://httpbin.org/get")
         .responseString { (_, _, string, _) in
                  println(string)
         }

It’s the most popular library for Swift to date, so you should probably be using it, right?

Well, maybe… The library makes some common tasks simpler and less verbose, but if you don’t know the basics of networking in Swift (or Objective-C), it’s probably best to get a good understanding of the existing APIs first. After understanding what’s going on under the hood, you can make a more informed decision about whether or not you need the extra layer of abstraction. Alamofire is a big framework, and networking is a huge topic, so I don’t want to get too far in to the details on this library. But, suffice to say if you are working with complex networking requests with lots of back and forth with a web server, and/or working with a complicated authentication process, using Alamofire might reduce some of the repetitive coding tasks. If you are new to iOS development, I would recommend just stick to the APIs provided by Apple for now.

SwiftyJSON

SwiftyJSON is “The better way to deal with JSON data in Swift” according to it’s Github entry. This framework is one of the first I saw when Swift was first released, that combined with the fact that JSON parsing is such a common problem is how it became a top repository, helping to deal with the messiness of Apple’s built-in JSON parser. In particular, the static typing of Swift and optional syntax led to a lot of verbose JSON parsing code, guessing and checking each step of the way for each key and checking every cast. The truth is though, using this library is VERY similar to just using optional chaining and Swift’s normal casting syntax. There is not much benefit here, and from what I’ve seen in production, SwiftyJSON has some performance problems, as a result I’m not sure I would recommend using it right now, except in prototype apps, or during the learning phase.

Take a look at the example they give as the standard approach to parsing JSON, which they describe as “not good”:

let JSONObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)

if let statusesArray = JSONObject as? [AnyObject],
   let status = statusesArray[0] as? [String: AnyObject],
   let user = status["user"] as? [String: AnyObject],
   let username = user["name"] as? String {
    // Finally we got the username
}

They then present their alternative version of the syntax:

let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string{
  //Now you got your value
}

There’s a few issues here, first of which is that the simplifications they are showing are partially just taking advantage of language features that would actually work with the regular parser. Second, it seems like their example actually would not work.

Based on the example code shown above, the example JSON they are parsing looks something like this:

{
    "statuses": [
        {
            "user": {
                "name": "Bob"
            }
        }
    ]
}

One issue with this sample right off the bat is that they are casting the initial value of the JSON to an array, which would suggest that the root element is an array, which is invalid JSON. The type of the root object in valid JSON is always going to be a key/value. Or equivalently in Swift, a Dictionary of type [String:AnyObject]. Additionally, it’s good practice to actually check if the JSON parsing succeeded or not.

Once we start going through and fixing all the issues with the sample code, assuming we want to explicitly cast everything as they have shown, we end up with something like this:

if let JSONObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [String:AnyObject],
    statusesArray = JSONObject["statuses"] as? [[String:AnyObject]] {
        let status = statusesArray[0] as [String: AnyObject]
        if let user = status["user"] as? [String: AnyObject],
            let username = user["name"] as? String {
                println("username: \(username)")
        }
}
else {
    println("Failed to parse JSON, handle this problem")
}

Now, this is in fact pretty verbose, and could be reduced quite a bit, but let’s stop a think about what we’re doing here. In this example, we are trying to download a list of statuses which are owned by users, and they have names. In an actual Swift application, I would expect there to be a model representing these objects. Maybe something like this:

struct User {
    let name: String
}
struct Status {
    let user: User
}

Assume we are using SwiftyJSON for a moment, how would we add these records to the model of our app? Maybe with a bit of code like this…

struct User {
    let name: String
}
struct Status {
    let user: User
}

let parsedJson = JSON(data: data)
for (key, val) in parsedJson["statuses"] {
    if let username = val["user"]["name"].string {
        let owner = User(name: username)
        let newStatus = Status(user: owner)
    }
}

This works relatively well, assuming we are just creating objects from a JSON feed rather than synchronizing them. But what if there is a server error and the JSON comes back invalid? For example if there is a server error which changes the JSON to present an “error” key, and it no longer includes “statuses”, this loop simply would not be executed. Failing silently is better than crashing, but it would be nice to check for issues and try again, or adjust something in the app.

Since we need to check for the presence of statuses, and this for loop doesn’t actually do that, we need to check the count of statuses first, which means we need to cast it to an array, and *then* check the count…

if(parsedJson["statuses"].count<1) {
    println("Oops! An error occurred")
}

And that's that! Right?
Well, no...

If the key isn't defined, this count property evaluates to 0, which could just mean there is no new statuses to see. The count really should not be zero, it should be null.. but SwiftyJSON is telling us it's 0. This seems like the kind of thing I really *don't* want a JSON parser to be doing. They really seem to not like the optional syntax in Swift, and instead reinvented it with these type properties. Why not just stick with convention?
Our final code might look something like this:

struct User {
    let name: String
}
struct Status {
    let user: User
}

let parsedJson = JSON(data: data)
for (key, val) in parsedJson["statuses"] {
    if let username = val["user"]["name"].string {
        let owner = User(name: username)
        let newStatus = Status(user: owner)
    }
}
if(parsedJson["statuses"].count<1) {
    println("Oops! An error occurred")
}
if let err = parsedJson["error"].string {
    println(err)
}

Our code is starting to grow, and this doesn't cover a ton of things we would need in a real-world application, such as updating the model, including more properties, checking for equality, enforcing uniqueness, cascading relationship changes, and a host of other things. Core Data can handle much of this, and it's common practice to implement models as Core Data models, but that still creates a situation where we have to custom implement all kinds of methods for converting the entire model object (such as Status) *back* in to JSON to update the server.

In the Objective-C world there is Mantle, a great library for handling such things. Before that there was RestKit. RestKit however made some ...interesting... design decisions a few years ago in a big update, and haven't ever really recovered since then. Unfortunately I haven't found a good solution for Swift just yet, and trying to work with Mantle proves to be problematic in it's current form, unless you implement all your models in Obj-C, something I'm not sure we all want to do at this stage.

I know this isn't all problems with SwiftyJSON, but they ironically break a lot of Swift conventions in dealing with optional values. SwiftyJSON is really a terrible name, they are very much not Swifty at all. However, the syntax is a little easier on the eyes. Personally, I don't use the library in my projects.

Spring

Spring is "A library to simplify iOS animations in Swift." How does it do this? Let's take a look.

Trying out some sample code I threw together this quick demo UIViewController that adds a blue square to the screen and animates it in, give it a try yourself, it's pretty nifty:

import UIKit
import Spring

class ViewController: UIViewController {
    var square = SpringView(frame: CGRectMake(0, 0, 200, 200))
    override func viewDidLoad() {
        super.viewDidLoad()
        
        square.center = self.view.center
        square.backgroundColor = UIColor.blueColor()
        square.animation = "squeezeDown"
        square.animate()

        self.view.addSubview(square)
    }
}

The SpringView seems to basically just be a UIView subclass with the animations added in. I don't know if I really like the idea of having to use their UIView, but I suppose most of the time I just use the basic UIView, and even if I didn't, I could just subclass SpringView instead.

Spring sports quite a few animation types, set as a string. The square.animation = "squeezeDown" here is what's determining the animation to play. The library goes beyond this, and in fact allows simple animations to be created in storyboards. So in theory you could put Spring in your Xcode project, and then pass it off to a designer to set up some nifty animations using this library. Very interesting idea, I would like to hear from someone who has tried to do exactly this.

Quick

Quick is "The Swift (and Objective-C) testing framework."

Really? It's THE testing framework? Let's take a look at how Quick works as opposed to XCTest, or expecta.

In XCTest, you might define an assertion that you're testing against like this:

class JSONSwiftTests: XCTestCase {
    
    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }
    
    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }
    
    func testContrivedExample() {
        let name = "jameson"
        XCTAssertEqual(name, "jameson", "Name should be \"jameson\"")
    }
}

This is okay, it makes the test basically confirm that name is equal to "jameson". It's simple enough, but there is a common trend/desire among developers to instead express test cases in terms of desired behavior, rather than specifically implementing what the desired behavior causes. Those may sound like the same thing, but take a look at how Quick (due to it's usage of the library Nimble) expresses the same thing like this:

import Quick
import Nimble

class AQuickTest: QuickSpec {
    override func spec() {
        describe("the user") {
            it("has the name 'Jameson'") {
                let name = "Jameson"
                expect(name).to(equal("Jameson"))
            }
        }
    }
}

More than anything else, this framework encourages behavioral tests, which is why this example includes more information about our expectations.

Quick also eases some of the pain of asynchronous testing. In XCTest I personally tend to use XCTestAsync, although Xcode 6 does introduce a way to do this using XCTestExpectation. The basic way that works is you can create an expectation object, and then fulfill it when the async operation is complete. It's not a bad approach.

import Quick
import Nimble

@objc class AsyncExample {
    var longTaskIsDone = false
    var timer: NSTimer?
    func startLongTask() {
        timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "taskIsDone", userInfo: nil, repeats: false)
    }
    func taskIsDone() {
        println("task done")
        longTaskIsDone = true
    }
}

class AQuickTest: QuickSpec {
    override func spec() {
        describe("the user") {
            it("has the name 'Jameson'") {
                let name = "Jameson"
                expect(name).to(equal("Jameson"))
            }
        }
        
        describe("Async Example") {
            describe("its long task") {
                it("should finish in 5 seconds") {
                    let asyncExample = AsyncExample()
                    asyncExample.startLongTask()
                    expect(asyncExample.longTaskIsDone).toEventually(beTruthy(), timeout: 3, pollInterval: 0.4)
                }
            }
        }
        
    }
}

In this example we just create an NSTimer that fires in 2 seconds, as a simulated async example. Then in the Async Example test, we can use the .toEventually() method to wait around and keep checking in to the asyncExample.longTaskIsDone property. This is slightly cleaner in that using expectations, because with this method we don't need to change our code to make sure the test is notified of this variable changing. Having an ongoing timer keep checking is great (just be careful not to have it calling methods with side effects!)

Overall Quick seems pretty interesting, the approach is sure to appeal to those in professional environments, or working with an Agile team where specs change fast.

That's it for this time, if you would like to see any of these libraries covered in greater detail be sure to let me know. You can find me on Twitter.


Sign up now and get a set of FREE video tutorials on writing iOS apps coming soon.



Subscribe via RSS

Should I learn Objective-C or Swift first?

“Should I learn Objective-C or Swift first?”

I get asked this question a lot. Sometime’s people will also ask about learning C or C++ first. So, I want to take a moment and give you the low-down on how I feel as a professional iOS & Mac developer, six months after Swift’s introduction. If this is your first time here, here’s a little background on me:

About me…

I’ve been developing software for as long as I can remember, at least 20 years now. I never was really the Mac guy, but I liked Linux and was always looking at new technologies. So, when the iPhone came out in 2008, I got myself a Mac and entered that ecosystem. Around that time I learned Objective-C, and that became my primary development language. It has been since then, and I’ve seen the language and Mac/iOS APIs twist and turn this way and that for the past 6+ years. In June I picked up Swift for the first time like everyone else, and although I still won’t call myself an expert, I will say I’ve done extensive study on the language. I’ve developed (and released) 3 apps using Swift since the announcement. Learning Swift is something I think is really important to iOS developers now, in fact it’s critical. To help people out I decided to write my Swift Book. This also serves as a way to help me learn the language, but I have already seen what a valuable resource it is for others; it’s exciting to be a part of… Additionally I’ve worked on an SDK that uses Swift, which will be used as part of a major platform worldwide in 2015. It’s very exciting to ship something like this that so many other developers will be using.

So, that’s my Swift-related experience in a nutshell. Now, here’s how I want to answer your question…

So… Swift or Objective-C?

Part of me wants to say, “Yes, go learn C first and then Objective-C. That’s what I did, so that’s what you should do.”

But here’s the thing: Just because that’s the path I took, doesn’t mean it’s the best path today. When I was first learning C, people told me I needed to learn Assembly to really get what was going on. They told me that without an underlying understanding of Assembly, I was going to be forever writing code and not understanding it. I ended up ignoring this advice and was very happy and successful as a developer without Assembly knowledge. In my college years, I finally picked up Assembly as part of my Electrical Engineering degree program. It helped enlighten some things, but for the most part I don’t feel knowing Assembly had much of an effect on my day-to-day programming. It had no effect on how I separate objects, how I decide what gets encapsulated, where to inherit, or where to compose. Most importantly, it didn’t help me to build better software. It was basically just academic, and as interesting as it was and is, the only place it’s even remotely relevant day-to-day is in debugging or reverse engineering; and only in limited capacities.

There’s certainly some sort of fear in me, like if we don’t all learn Assembly it will become a lost art. But, I don’t think that’s a realistic concern, honestly. The more I think about the idea of Assembly becoming a lost art the more I realize it will never happen. A single preserved book on the topic can get anyone where they need to be to be productive in Assembly, you just probably don’t want to.

Computer Science is an industry where we need to let go of the past, and we need to do it as quickly as we can. This industry is not going to wait for you to learn all the languages leading up to the latest and greatest. The marketplace certainly won’t reward that. What it will reward though, is knowing how to write code to make working software. That’s sort of the general thesis of this site, and it’s why I produce it. I don’t want to teach you to write code; I want to teach you to make software.

So here’s my answer to your question:

Swift

You should learn Swift first. You should learn it first because it’s the future of development on Apple platforms, and frankly it’s just easier to understand than Obj-C or C. What you may find as you learn it is that the Cocoa framework is getting a little stale. It’s starting to look very much like an Objective-C API in a Swift world. But that’s probably going to change. This wouldn’t be the first time Apple made a major change to their underlying APIs. Back in the days before Cocoa developers used Carbon, a C-based API that had some interoperability with Objective-C.

Apple is well-known for making swift (get it?) changes to their development stack. The move from Mac OS 9 to Mac OS X is a great example of their commitment to innovation. As a developer on Apple platforms, it’s important to understand this fact. Apple is about building the future of technology products, and they are not afraid to forego backwards-compatibility in order to achieve that. If you are still writing Objective-C day-to-day, you’re writing legacy code at this point. If you are writing Swift, then welcome to our world, you are the future.


Sign up now and get a set of FREE video tutorials on writing iOS apps coming soon.



Subscribe via RSS

Running Swift Scripts From The Command Line

Swift Scripts From The Command Line

This post updated for Xcode 6.1

One of the great features of swift is it’s ability to be used on the command line. It’s actually really easy to do, and I’ll show you how to make an executable Swift file in this tutorial.

First let’s create a new Swift file. In any text editor, create a new file and save it as Hello.swift.

In order to make this file executable we need to give it permissions. In the terminal app, navigate to your file using the cd command, and then type this:

chmod +x Hello.swift

Now open up your Swift file. We’re going to tell it to use xcrun to run our code.
First, let’s get a simple script going that prints a response to the console:

#!/usr/bin/env xcrun swift

println("Hello World!")

This is great, but what about arguments? It’s very common for a script to take some arguments, do something with them, and then return a result.
Let’s say we wanted to make a command line utility that takes any number of numbers as arguments, and just adds them together. We’ll call it SwiftSum.

A reasonable first step in building this script would be to simply print out the command line arguments. Similar to other languages, Swift automatically creates an argument count variable and argument value pointer.

C_ARGC is the number of arguments passed in
C_ARGV is an array of the argument’s values

We can loop through the arguments and print them fairly easily…

#!/usr/bin/env xcrun swift
for i in 1..<C_ARGC {
  let index = Int(i)
  if let argStr = String.fromCString(C_ARGV[index]) {
    println(argStr)
  }
}
SwiftSum.swift 1 2 3

Outputs:

1
2
3

If we want to add these, we just need to attempt converting them to an Int, and if that succeeds add it to a total…

#!/usr/bin/env xcrun swift

var total : Int = 0

for i in 1..<C_ARGC {
  let index = Int(i)
  if let argStr = String.fromCString(C_ARGV[index]) {
    if let argInt = argStr.toInt() {
      total += argInt
    }
  }
}

println(total)
$ ./SwiftSum.swift 1 2 3

Outputs:

6

In my book I talk more about using Swift from the command line, so I hope you choose to follow along. If not, make sure you subscribe to get the latest tutorials from me.


Sign up now and get a set of FREE video tutorials on writing iOS apps coming soon.



Subscribe via RSS

Using open source iPhone app components with Cocoa Pods

For a while after the initial release of the iPhone App Store and it’s SDK, there was not much in terms of open source code to use and learn from. But times have changed, and these days there is a huge database of open source components, and even full projects ripe for use in your next app.

This post is a bit of an instructional guide for those looking to take advantage of open source in their iPhone projects. Whether you are new to iOS, a seasoned developer, or a project manager, you can benefit from this short guide.

Currently, the biggest repository of open source iOS components is CocoaPods. The official list of components, known as “Pods’, is maintained in a Github repository located here: https://github.com/CocoaPods/Specs

Unfortunately this list is not particularly easy to browse. To find out the details of any one Pod, you have to select one from the list, pick a version, open the.podspec file, and then pick out the description in the file. Fortunately for you, the handsome reader, you can browse a (possibly slightly out of date) list of these Pods on the site https://www.cocoacontrols.com/cocoapods, in a much more easy to digest format.

So how do you use these? If you’ve got a ruby install set up with ruby gems, you can just navigate to your project directory and create a Podfile file, with no extension. It looks like this:

platform :ios, ‘6.0’

pod ‘TestFlightSDK’, ‘>= 1.1’
pod ‘SVProgressHUD’
pod ‘iRate’
pod ‘TimesSquare’, ‘1.0.1’
pod ‘AFNetworking’, ‘1.1.0’
pod ‘iCarousel’

Once you’ve created this Podfile you can run this command in Terminal:

$ pod install

If it gives you some kind of error, you might need to install Cocoa Pods. If that’s the case you first need to run this:

$ gem install cocoapods

And if that doesn’t work, then you still need ruby gems, and maybe even ruby.

Once you generate the pod install, make sure you close your Xcode project if you already have it open, and from now on use the .xcworkspace file when working on your project. What you’ll find is that Cocoa Pods has now created a subproject for your Pods. Yay! This means you can now compile your dependencies separately from the project, and changes to your project shouldn’t call for a full recompile. More importantly, you can easily update your dependencies by just modifying your Podfile, and running ‘pod install’ again.

So to recap:

1. Install ruby

$ \curl -sSL https://get.rvm.io | bash -s stable

2. Install ruby gems if you don’t have ut

Visit http://rubygems.org/pages/download

3. Install cocoapods

$ gem install cocoapods

4. Create a Podfile in your Xcode project directory

5. Add any relevant pods you might want to use. At this stage I do not specify a version, I let it use the most recent, and then lock it to that version to avoid unwanted updates. I’ll later remove the version specification when I feel it is time to get everything up to date.

6. Run pod install

$ pod install

7. Open your project from the xcworkspace file instead of the xcodeproj file.

8. Enjoy!

Related article: 8 Great Open Source Projects to use in your next iPhone App


Sign up now and get a set of FREE video tutorials on writing iOS apps coming soon.



Subscribe via RSS

The lazy app developer’s way to ship more code

With these three quick tips, you’ll be on your way to being more productive when developing your mobile apps. These are not extremely difficult technical challenges, and should be easy to implement in to your workflow.

 

Dependency Management

If you’re on iOS, Cocoapods is a godsend. If you’ve ever used bundler with Ruby on Rails, you’ll be familiar with this concept. A series of dependencies for your iOS app are listed out in a human readable format in a Podfile, which is then used with the ‘pod’ command line utility to download, update, install, and check frameworks for compatibility. In the old days iOS developer’s would have to manually manage the importing and linking of every library used, but now cocoapods does the heavy lifting for you. If you’re not using it yet, go check it out. Cocoapods will help you leverage more open source code, more effectively, in less time.

 
Automated testing

One of the most time consuming parts of developing an iOS app can be performing tests of your application using the device (or iPhone simulator.) But many of the tests you are performing can be partially implemented using the now-default OCUnit testing suite. OCUnit does some nice things, but to truly automate all your actual use testing, look in to Calabash. It’s basically cucumber for iOS, and allows for UI-based testing of apps. By writing proper tests, you can automate almost all testing, find bugs faster, and resolve UI issues before they become serious problems. Not only does automated testing speed up the process of development, but it enables you to ship higher quality code.

Design before you build

I mean this on multiple levels. First, before you begin writing any code, it is a good idea to have a solid concept for your app, along with all the needed features for marketing and promotion.

Second, designing your UI up front can save you a LOT of time and frustration during the development process. Changing the way a button behaves in a Photoshop file after thinking about it a bit, is *much* easier than trying to change it after code has been implemented. Be as certain as possible of your UI before committing any code.

Third, before you (or your programmers) move in to the actual code, it’s important to plan out how every object should exist, and how they should relate to each other. This is basic software planning, but I’ve seen it skipped too many times to not bring it up. Taking this basic step ahead of time can be the difference between a project that completely misses it’s schedule, and a project that is delivered under budget and ahead of time.

 

Related article: Top 10 Lessons Learned from Launching iPhone Apps


Sign up now and get a set of FREE video tutorials on writing iOS apps coming soon.



Subscribe via RSS

8 Great Open Source Projects to use in your next iPhone App

I’ve scoured the internet looking for great open source iOS apps, and what I determined is that what is really more interesting is the open source iOS components and frameworks. So here’s my list of the most useful open source iOS components.

8. PSCollectionView
PSCollectionView is a custom collection view that allows for the easy creation of Pinterest-style image collections in your iOS apps. Source on Github

 

7. GMGridView
This little grid view library allows for the simple creation of highly interaction view sets. You can see a nice video of an example result hereSource on Github

 

6. PRTween

PRTween is an extension of the core animation framework. It is an effort to take the power of core animation, and make it easier to use. The commands available may remind some of the stupid-simple jQuery animation commands like fade, hide, or show. Source on Github

 

 

5. iHasApp
I recently was asked by a client if we could detect their other apps installed on the device, and if the user didn’t own them if we could have the app present cross-promotional ads. I wasn’t sure what the answer to their question was, it seemed like something that might fall under the dreaded “private api” category. But here this project is an App Store friendly library to detect other apps installed on the user’s phone. Source on Github

 

4. NUI
NUI is a very interesting project that aims to make styling of iOS apps as easy as styling in CSS. Take a look at the syntax on the project’s github page and you’ll see what makes this such an interesting project. Source on Github

 

3. grabKit
If you are writing an iPhone app that involves the user’s photos, one thing that’s always a bit tricky is adding support for all the various social networks that the user might prefer to host their photos on. grabKit makes this easier with this drop-in library that let’s the user import photos from Facebook, Flickr, Instagram, Picasa, or the iOS device itself. Source on Github

 

2. MultistrokeGestureRecognizer
This library is great for anyone creating a very touch-centric game, or any app that uses lots of complex gestures. The library is based on the N Multistroke Recognizer which is a great algorithm for detecting very complex touch gestures. If you remember the gestures in the game Black & White, it’s kind of like that. Source on Github

 

1. Filepicker
Similar to grabKit, Filepicker allows for the importing of files from various social networks, but also includes many more services such as Dropbox, Gmail, and even Github. The library is also not limited to only photos but can be used for a range of content types. Source on Github

 

Honorable mention: cupertino
Cupertino is not an iOS library, but rather a ruby gem that allows for administration of your Apple Developer Account. This has been a missing piece of the formula for automating iOS development work for years, so I’m glad to see some hackers have decided to take up the challenge of making a CLI for the Apple Developer Account system.


Sign up now and get a set of FREE video tutorials on writing iOS apps coming soon.



Subscribe via RSS