Viewing entries in
iOS development

Intro to CocoaPods

Comment

Intro to CocoaPods

CocoaPods is cool. Due to my bad memory, I'm going to write here the steps I need to perform to profit from it.

What it does

Cocoapods simplifies the use of external source code in your project.

Installation

The first step is to set up the computer:

sudo gem update --system
sudo gem install cocoapods -V

Alternatively, instead of using sudo, you can install in you user directory as explained here.


Note: When recently updating I encountered the following error message:

ERROR:  While executing gem ... (Errno::EPERM)
    Operation not permitted - /usr/bin/xcodeproj

The solution (described here) was to run:

sudo gem install cocoapods -n /usr/local/bin

This can take some time. The optional -V prints additional stuff and gives confidence that something is going on. The same command can be used to udpate cocoapods. With that done, cocoapods should be installed in the computer. How can you check it works? Well, simply try:

pod

You should get something like this:

Setting up CocoaPods master repo

CocoaPods 0.35.0.rc2 is available. To update use: gem install cocoapods --pre [!] This is a test version we'd love you to try.

For more information see http://blog.cocoapods.org and the CHANGELOG for this version http://git.io/BaH8pQ.

Setup completed Usage:

$ pod COMMAND

  CocoaPods, the Objective-C library package manager.

Commands:

+ init                Generate a Podfile for the current directory.
+ install             Install project dependencies to Podfile.lock versions
+ ipc                 Inter-process communication
+ lib                 Develop pods
+ list                List pods
+ outdated            Show outdated project dependencies
+ plugins             Show available CocoaPods plugins
+ push                Temporary alias for the `pod repo push` command
+ repo                Manage spec-repositories
+ search              Searches for pods
+ setup               Setup the CocoaPods environment
+ spec                Manage pod specs
+ trunk               Interact with the CocoaPods API (e.g. publishing new
                      specs)
+ try                 Try a Pod!
+ update              Update outdated project dependencies and create new
                      Podfile.lock

Options:

--silent              Show nothing
--completion-script   Print the auto-completion script
--version             Show the version of the tool
--verbose             Show more debugging information
--no-ansi             Show output without ANSI codes
--help                Show help banner of specified command

Setup

To use cocoapods in a project you need to create a Podfile with information on which cocoapods you want to use. This file contains the dependencies of your project. An example:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
pod 'AFNetworking', '~> 2.0'
pod 'ARAnalytics', '~> 2.7'

This file must be located in the same directory as your xcodeproj file.

You can create a Podfile with:

pod init

The contents of this default file look like (created for a project called XXX):

Uncomment this line to define a global platform for your project
platform :ios, '6.0'

source 'https://github.com/CocoaPods/Specs.git'

target 'XXX' do
end

target 'XXXTests' do
end

The two targets that were created are inherited from the parent folder where the Podfile is created. These targets are default from Xcode.

Once you create the Podfile, you can download the code with:

pod install

For the generated Podfile above, the results is:

Analyzing dependencies

CocoaPods 0.35.0.rc2 is available.
To update use: `gem install cocoapods --pre`
[!] This is a test version we'd love you to try.

For more information see http://blog.cocoapods.org
and the CHANGELOG for this version http://git.io/BaH8pQ.

Downloading dependencies
Generating Pods project
Integrating client project

[!] From now on use `CocoapodsTest.xcworkspace`.

[!] [!] The Podfile does not contain any dependencies.

A new XCode workspace (extension xcworkspace) will be created. This workspace will include your original project. The dependencies you defined in the Podfile will be added to this workspace. In addition, the following is created:

  • Podfile.lock
  • Pods

The Pods directory contains an Xcode project (Pods.xcodeproj) used to build the pods you added.

The Podfile.lock file contains the versions of the pods that were donwloaded.

The podfile

See info on the podfile

Other articles

For details of how CocoaPods works under the hood, check this ObjC.io article.

Comment

Comment

Fetching data with NSURLSession

It turns out that getting some file from the internet is relatively easy with the new NSURLSession API.

A simple example:

brush: swift
let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
var dataTask: NSURLSessionDataTask?

func fetchData(sender: AnyObject) {
    if dataTask != nil { dataTask?.cancel() }
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    let url = NSURL(string: "http://localhost:8000/a.json")

    dataTask = defaultSession.dataTaskWithURL(url!) {
        data, response, error in
        dispatch_async(dispatch_get_main_queue()) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible =   false
        }

        if let error = error {
            print(error.localizedDescription)
        } 
        else if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode == 200 {
                self.updateData(data)
            }
        }
    }
    dataTask?.resume()
}

By the way, it turns out that fetching simple http is no longer the advised way. Only https is accepted out of the box. To allow http for testing, you need to add the following to the Info.plist:

  • App Transport Security Settings
    • Allow Arbitrary Loads: YES

Based on this article

Comment

Comment

Parsing JSON in Swift

Parsing JSON files is easy as long as you remember that all the Data is of type AnyObject and that you can try to cast the fields to String or Int as needed. An array is of type [AnyObject], a dictionary of type [String: AnyObject], a string of type String and an integer of type Int.

We will write some code to parse this very simple JSON file:

{
  "people": [ "bob", "rob"]
}

The code to parse this is:

brush: swift
  func parseJSON(data: NSData?) {
    do {
      if let data = data, response = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions(rawValue:0)) as? [String: AnyObject] {   
        // people is an array
        if let array: AnyObject = response["people"] {
          for person in array as! [AnyObject] {
            if let name = person as? String {
              // Do something with the name
              postNameInObscureBlog(name)
            } else {
              print("Not a string")
            }
          }
        } 
        else {
          print("people key not found in dictionary")
        }
      }
      else {
        print("JSON Error")
      }
    } catch let error as NSError {
      print("Error parsing results: \(error.localizedDescription)")
    }
  }

Comment