How to Use cocoapods (manage Ios to develop third-party class libraries)

Source: Internet
Author: User
Tags install cocoapods
ArticleDirectory
    • Install rubygems
    • Install command line
    • Install cocoapods
Http://ijavascripter.com /? P = 47

This article describes how to use cocoapods. Cocoapods is a dependency management tool.

So what is a dependency management tool? Why do we need this tool?

As an iOS developer, you must use a third-party library. NormallySource codeDirectly join our project (it is boring to manually create a static library), but there are some disadvantages:

    • Waste of space. SourceCodeIt may already exist in your code hosting
    • Sometimes it is difficult to obtain a third-party library of a specific version.
    • There is no centralized place to view which libraries can be used now
    • Updating a new version is boring and sometimes painful.

A dependency management tool can help you overcome most of the problems mentioned above. It will help you download the source code of the library you use, create and maintain the environment you need.

This article uses cocoapod to create an application that gets information about your programs on trakt. TV.

You will find the benefits of using cocoapods.

Cocoapods's official website describes its own "the best way to manage library dependencies in objective-C Projects ". For the time being, it is not virtual.

Instead of downloading code from GitHub and copying it to your project, it is better to have cocoapods help you complete this job.

The requirement of trakt. TV is that we want to create an application to display the information of the TV programs to be played.

Install cocoapods to install rubygems

Cocoapods requires a ruby environment. Fortunately, all Mac computers are pre-installed with Ruby, so you need to update your rubygems (if your system version is earlier than OS X Lion)

You only need to enter the following command to update your rubygems:

Sudo gem update -- System

Install command line

Make sure that you have installed the command line tool in your xcode ). In the latest Mac OS X lion and xcode, the command line tool is not installed by default. You can install command line tool as follows:

    • Download from here and install
    • Open xcode and open the components interface. Xcode-> preferences-> downloads-> components. There should be a "command line tools" option, followed by the "Install" or "Update" button, just click the button. After the installation is complete, the text of the button changes to "installed ". For example:
Install cocoapods

After completing the preceding steps, run the following command to install cocoapods:

Sudo gem install cocoapods

Pod setup

The first installation may take some time. Please wait.

Create a cocoapodsexample Project

Open xcode and create a project based on "single view application. The project name is "cocoapodsexample", "Device Family" is "iPhone", and "use storyboards" and "use automatic reference counting" are selected ". For example:

Click Next and select a place to store your project.

Find an image as launch images. If no combination is available, you can download this -placeholder.png. Drag the image to the project and select "Copy items into destination group's folder (if needed )".

Open belowMainstoryboard. storyboardAnd follow these steps:

    1. Add a scroll view. Make sure that the width and height of the scroll view are 100%
    2. Modify the attributes of the scroll view. Open the attribute selector, without selecting "shows horizontal scrollers" or "shows verticall scollers ". Select "scrolling enabled", "Paging enabled", and "direction lock enabled"
    3. Add a page control. Make sure that the page control is the sibling view of the previous scroll view, instead of the subview of the scroll view. The page control should be in front of the scroll view, otherwise you will not be able to see the page control.

Storyboard should look like:

Finally, we connect scroll view and page view to an outlet. we name the outlet of scroll view as showsscrollview, and use the current view controller as the delegate of scroll view. Name the outlet of page control as showpagecontrol and bind a method to the "value changed" event of page control. The method name is pagechanged.

Now you can turn off your xcode, and the next step is to create your podfile.

Create your first dependency

Open the terminal and open the folder that stores your "cocoapodsexample" project. Run the following command:

 
Touch podfile
 
Open-e podfile

Textedit will be opened. You can add content to the opened blank podfile.

Add the following content to podfile:

Platform: IOS pod 'afnetworking', '0. 123'

As you can see, the format of podfile is very simple. First, set platform to IOS (because some frameworks only support one of iOS or Mac OS X, rather than all of them ). Then, you add your first dependency-"afnetworking" and specify it. What you need is 0.9.1.

Edit podfile. In addition to the above method, you can also use other editing tools you like, such as Vim

For more information about the podfile format, see a podfile and podfile (frames ).

After saving the podfile, we can start to configure your project.

Run the following command on the terminal:

 
Pod install

After the execution, you should see the following in the terminal:

If you open the folder where your project is located, you will see:

Cocoapods creates a folder named "pods", which stores all dependent libraries and a workspace file, cocoapodsexample. xcworkspace

Very important!

From now on, youRequiredOpen a project with a workspace file (cocoapodsexample. xcworkspace), instead of using a project file (cocoapodsexample. xcodeproj)

Test afnetworking

To test whether afnetworking has been successfully added to cocoapods, you can create a Class Based on IOS/cocoa touch/objective-C class, which is called sktraktapiclient and is a subclass of nsobject. Remember to add this class to cocoapodsexample instead of the pods project. If you take a look at the navigation of your project files, you will see two independent projects: cocoapodsexample and pods

OpenSktraktapiclient. hAnd replace the existing code with the following code:

 
# Import extern nsstring * const ktraktapikey; extern nsstring * const ktraktbaseurlstring; @ interface sktrakeapiclient: afhttpclient + (sktrakeapiclient *) sharedclient; @ end

The above Code does the following:

    1. The first line of code imports the header file of the Foundation
    2. The second line of code imports the afnetworking header file. afnetworking will be the header file of sktraktapiclient.
    3. Two variables are set for the next two rows.
    4. Finally, we define a method that returns an independent sktraktapiclient strength.

Why should we create a sktraktapiclient class when afnetworking can process all HTTP requests? The reason is that we want a class to process all our requests with trakt. TV and use the same base URL and API key. This facilitates subsequent maintenance.

Open nowSktraktapiclient. mAnd use the following code to replace the existing code:

 # import "sktraktapiclient. H "# import nsstring * const ktraktapikey = @" Courier "; nsstring * const ktraktbaseurlstring = @" http://api.trakt. TV "; @ implementation sktraktapiclient + (sktraktapiclient *) sharedclient {static sktraktapiclient * _ sharedclient = nil; static dispatch_once_t oncetoken; dispatch_once (& oncetoken, ^ {_ sharedclient = [self alloc] initwithbaseurl: [nsurl Urlwithstring: ktraktbaseurlstring];}); Return _ sharedclient;}-(ID) initwithbaseurl :( nsurl *) URL {self = [Super initwithbaseurl: url]; If (! Self) {return nil;} [self registerhttpoperationclass: [afjsonrequestoperation class]; [self setdefaultheader: @ "accept" value: @ "application/JSON"]; self. parameterencoding = afjsonparameterencoding; return self ;}@ end 

First, we importedAfjsonrequestoperation. hIn this way, all returned values are in JSON format. We have created a sharedclient, where gcd (Grand Central Dispatch) is used to ensure that the Singleton that implements sktraktapiclient is free as long as the sktraktapiclient obtained through the sharedclient method is the same instance, it will not be created again. In addition to this, we have also rewrittenInitwithbaseurlThe reason is that all subsequent methods created using initiwithbaseurl have the same response format-JSON format.

Open belowAppdelegate. mAdd the following code:

 
# Import

InApplication: didfinishlaunchingwitexceptions:Add the following code:

 
[Afnetworkactivityindicatormanager sharedmanager]. Enabled = yes;

The above Code enables the automatic network activity indication manager, which is a function supported by afnetworking. In this way, you do not need to open activity indication every time you send a request, and then close activity indication.

Open nowViewcontroller. mAnd add the following code:

 
# Import "sktraktapiclient. H" # Import

Use the following code to replace viewdidload:

-(Void) viewdidload {[Super viewdidload]; // 1-create trakt API client sktraktapiclient * client = [sktraktapiclient sharedclient]; // 2-create date instance with today's date nsdate * today = [nsdate date]; // 3-create date formatter nsdateformatter * formatter = [[nsdateformatter alloc] init]; formatter. dateformat = @ "yyyymmdd"; nsstring * todaystring = [formatter stringfromdate: Today]; // 4-create API query request nsstring * Path = [nsstring stringwithformat: @ "User/calendar/shows. JSON/% @/% d ", ktraktapikey, @" marcelofabri ", todaystring, 3]; nsurlrequest * request = [client requestwithmethod: @ "get" Path: path parameters: Nil]; // 5-create JSON request operation afjsonrequestoperation * operation = [afjsonrequestoperation jsonrequestoperationwithrequest: Request success: ^ (nsurlrequest * request, nshttpurlresponse * response, Id JSON) {// 6-request succeeded block nslog (@ "% @", JSON);} failure: ^ (nsurlrequest * request, nshttpurlresponse * response, nserror * error, Id JSON) {// 7-request failed block}]; // 8-start request [operation start];}

After compilation and running, you can see similar logs in your console:

It can be seen that cocoapods correctly configures afnetworking for us.

 

Attachment:Http://vdisk.weibo.com/s/kvEHc

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.