iOS development tutorial: How to create a cocoapod in Swift?

Source: Internet
Author: User
Tags uikit install cocoapods


Summary:Developers may be familiar with some of the more well-known open source cocoapods frameworks, but sometimes they may not be able to find a pod that just satisfies their needs, and this article explains in detail how to use Swift to create a cocoapods process.


This article is from: Raywenderlich, translation: Development technology Front, translator: Mrloong



You might be familiar with some well-known, open-source cocoapods frameworks, such as Alamofire or mbprogresshud, but sometimes you can't find a pod that fits your requirements, or you might want to divide a large project into smaller projects or reusable builds.



Fortunately, it's easy to create your own cocoapods.



If you've created a cocoa touch framework for your component, you've done most of the hard work. If you haven't created it, don't panic, because it's really simple.



If you're just creating a part of an iOS app, that's OK. You can easily create some new pods for the push classes and features used in special environments.



This tutorial ends with the how-to using CocoaPods with Swift. If you have never used cocoapods before, however, this is a prerequisite for this tutorial.


Start


Your top customer is an ice cream store, their ice cream is so popular that their counter doesn't keep up with customer orders and needs to create a simple iOS app that lets users order ice cream with their phone. You will start developing this application.



Download this starting item from here-this is the final version of how to use CocoaPods with S wift. This app has some pod development packages already included in the download, so you don't have to run pod install to install them.



Open Icecreamshop.xcworkspace, then click Main.storyboard, Views\storyboards & nibs to see how the app is laid out.



The following is a quick choose Your flavor Application scenario with the following core features:


    • Pickflavorviewcontroller:handles user interaction, such as when
    • The user selects an ice cream flavor.
    • Pickflavorviewcontroller: Handles user interactions, such as when a user chooses a taste of ice cream
    • Pickflavordatasource:is the data source for the collection view
    • that displays ice cream flavors.
    • Pickflavordatasource: is a data source that chooses ice cream flavors to try.
    • Icecreamview:is A custom view that displays an ice cream cone and
    • is backed by a Flavor model.
    • Icecreamview: is an ice cream custom model.
    • Scoopcell:is a custom collection view cell that contains a
    • Scoopview, which is also backed by an instance of the Flavor
    • Model class.
    • Scoopcell: Custom Collection The attempt to assemble a unit contains a scoopview, which is also a support class for the flavor model.





The owner of the ice cream shop liked the app very much, but they added a new requirement: they had to choose the same flavor style in their application.



Wait, that's not the original design, but for a NB developer, there should be no problem.






Can you guess how this function is done? Yes, you will integrate this functionality into your own cocoapod!.


build Your own pod.


Create a new Xcode project and select Ios\framework & Library\cocoa Touch Framework, then click Next:






Name the project Rwpickflavor and select the Swift language and click Next.



The project of this tutorial will be created in ~/documents/libraries, select the Documents folder in your home directory. If you don't have a libraries folder, click the New Folder button at the bottom and create it.



Finally, select the Libraries folder and click Create.



It is important to save the pods you have developed because you will refer to this directory during the local development of Podfile.



Under normal circumstances, when you use Cocoapods, you include relationships in your podfile:


Pod ' podname ', ' ~> 1.0 '
But when you develop your own cocoapod, you will create a special path locally, like this:
Pod ' mypodname ',:p ath = ' ~/path/to/folder/containing/my/pod '


There are two benefits of this approach:


    • For your pod, it is using the files on the local machine instead of getting them from the remote repository.
    • Normally, you don't need to select a pod to include in your app, because these choices will be overwritten the next time you run the pod install, and the pod will be re-read from the remote repository and overwrite the changed files.


You can use different locations to develop your pods, and in general I recommend that you put them in ~/documents/libraries. If you work with a team to develop a cocoapods extension as an extension home directory, you do not have to work hard to build an absolute path in the Podfile directory.



You can also use other cocoapods in your project as a project dependency for you to create cocoapod. You only need a podfile to manage your cocoapod dependencies.



Close Xcode, and then enter the following command at the terminal:


CD ~/documents/libraries/rwpickflavorpod initopen-a Xcode podfile


This is to create a new podfile and open it in Xcode.



Use the following command to update the podfile:


platform :ios, ‘8.0‘
use_frameworks!
target ‘RWPickFlavor‘ do
  pod ‘Alamofire‘, ‘~> 1.2‘
  pod ‘MBProgressHUD‘, ‘~> 0.9.0‘
end


This declares that Rwpickflavor will provide dependencies in Alamofire and Mbprogresshud.



Save and close Podfile, and then enter the following command at the terminal:


Pod Install


As you would expect, this will create a working range and install the various files you need.


Note: If pod install gives you any warning, then you may be using an older version. Swift is based on Cocoapods, especially Alamofire, which requires cocoapods version 0.36 or newer. Depending on the following command, you can detect the Cocoapods version you have installed.
Pod--version
If this is the reason for the low version, enter the following terminal command to install the latest version.
sudo gem install CocoaPods


Enter the following command to open and create a new rwpickflavor working interval.


Open Rwpickflavor.xcworkspace


Your project navigator should look something like this:






You now need to copy some of the existing files from Icecreamshop in the Rwpickflavor working range.



First create a group in Rwpickflavor.xcworkspace and copy the files you need.


    1. Categories
    2. Controllers
    3. Factories
    4. Models
    5. Views
    • Ice Cream
    • Storyboards & Nibs


Now drag and drop each file, in addition to Appdelegate.swift and Launchscreen.xib, from the icecreamshop.xcworkspace dragged into the rwpickflavor.xcworkspace, like this:






When prompted, make sure that every item that needs to be copied is copied and installed instead of a simple link.



When you are done, Rwpickflavor should have the following files:



Rwpickflavor


    • RWPickFlavor.h


Categories



Rgbacolorfromstring.swift


    • Controllers


Pickflavordatasource.swift
Pickflavorviewcontroller.swift


    • Factories


Flavorfactory.swift


    • Models


Flavor.swift


    • Supporting Files


Info.plist


    • Views
    • Ice Cream
    • Storyboard & Nibs


Main.storyboard



Now, open info.plist, locate the supporting files group, and delete main storyboard file base name.



Build and run, you should not see any errors, and you will see the "Ice Cream Shop" icon and the black background.





What about the image?


You may notice that you are not replicating the resources group, because you need to copy only background.jpg himself into the resources folder. Incomplete images.xcassets resource file.



First create a resources group in Rwpickflavor.



Next, select Images.xcassets in Icecreamshop, click on the right background, and select Show in Finder, like this.






Now drag the background.jpg into the Rwpickflavor's resources group. When prompted, still detects if each entry is installed. When you copy, remove the Images.xcassets original background from the Icecreamshop.



Finally, select your scene in Main.storyboard on the image of the Rwpickflavor update view, so reference background.jpg overrides background:






Believe it or not, the hardest thing to create is your pod.





cocoapods and Git


Since Cocoapods is a dummy boot, every pod will need to have his own git repository. If you already have a preferred git hosting, OK, you can use it as your repository.



If not, GitHub is a good choice because it is a well-known development platform with a lot of free open source projects. In this tutorial, we use GitHub, but you can also use the Git repository.


GitHub Settings


Start by creating or logging into your GitHub account.



Next, click on the top right + (create new) icon and select New repository to display as follows:






Enter the Rwpickflavor warehouse and select Create Repository. GitHub will create a new warehouse under your account. Then you will see the following screen with a quick setup that shows you the stored repository URL.






So the distance opened to now you need this URL in just a moment.



Now you need a second warehouse to rush to store all your private pods that you will use in this tutorial.



Open github.com in a new window, click the Create New icon again, and select New repository. The warehouse is named Rwpodspecs, select Create Repository.



Leave this tag so that it's easy to use when you need to use it.


Podspec Settings


Now you need to create a Rwpickflavor.podspec file for rwpickflavor,podspec containing the basic information, especially the name of the pod, the version and the URL of the git download



Enter the following command at the terminal:


cd ~/Documents/Libraries/RWPickFlavor
pod spec create RWPickFlavor
open -a Xcode RWPickFlavor.podspec


This is the created Rwpickflavor.podspec, which opens it in Xcode.



There are many good examples and documents by default, but you don't need most of them.





Pod::Spec.new do |s|
  # 1
  s.platform = :ios
  s.ios.deployment_target = ‘8.0‘
  s.name = "RWPickFlavor"
  s.summary = "RWPickFlavor lets a user select an ice cream flavor."
  s.requires_arc = true 
  # 2
  s.version = "0.1.0"
  # 3
  s.license = { :type => "MIT", :file => "LICENSE" }
  # 4 - Replace with your name and e-mail address
  s.author = { "[Your Name Goes Here]" => "[[email protected]_Email_Domain.com]" } 
  # For example,
  # s.author = { "Joshua Greene" => "[email protected]" }
  # 5 - Replace this URL with your own Github page‘s URL (from the address bar)
  s.homepage = "[Your RWPickFlavor Homepage URL Goes Here]"
  # For example,
  # s.homepage = "https://github.com/JRG-Developer/RWPickFlavor"
  # 6 - Replace this URL with your own Git URL from "Quick Setup"
  s.source = { :git => "[Your RWPickFlavor Git URL Goes Here]", :tag => "#{s.version}"}
  # For example,
  # s.source = { :git => "https://github.com/JRG-Developer/RWPickFlavor.git", :tag => "#{s.version}"}
  # 7
  s.framework = "UIKit"
  s.dependency ‘Alamofire‘, ‘~> 1.1‘
  s.dependency ‘MBProgressHUD‘, ‘~> 0.9.0‘ 
  # 8
  s.source_files = "RWPickFlavor/**/*.{swift}"
  # 9
  s.resources = "RWPickFlavor/**/*.{png,jpeg,jpg,storyboard,xib}"
end



It's like a podfile,podspec is written in Ruby. Be careful not to make any errors, or you may not be able to verify the success after installation.



What's going on here?


    • First you detail the basic information of the pod. Swift must be based on the minimum CocoaPods8.0 version or higher. If you specify a lower version, the pod does not install properly.
    • For the cocoapod version you specified, the Podspec is essentially a snapshot. When you update a pod, you will also need to update the PODSPEC version. All high-version degrees follow Semantic Versioning. If you don't have a similar version, check out how do I use Cocoapods in Swift? 》。
    • All pods must specify a license. If you don't, Cocoapods will warn you when you install. And you can't upload it to the branch.
    • Here, you can specify information about yourself, the pod author. Enter your name and e-mail address. Replaces those placeholder text.
    • Here you need to specify the page and URL of your pod. is simply copy and paste from the browser address bar to the GitHub homepage.
    • Create the first "Quick Setup" from above, and that part of the GIT download URL replaces the URL. It is best to use an HTTP or https:url to be more easily handled by other users. If you want you can also use the SSH URL, but you need to make sure that everyone on your team-no matter who needs access to cocoapod-already has its own public/private key against your Git host.
    • Here you need to explain your framework and pod dependencies.
    • Here you can specify a common source file based on file extensions, in which case you can explain '. Swift ' as an extension.
    • Finally, you can specify a resource based on the specified file extension.
Push git


You are finally ready to push the Rwpickflavor pod GitHub home page! Enter the following command at the terminal, then jump out of the prompt, enter your username and password to GitHub.


cd ~/Documents/Libraries/RWPickFlavor
git init
git add .
git commit -m "Initial commit"
git tag 0.1.0
git remote add origin [Your RWPickFlavor Git URL]
git push -u origin master --tags


This all files in the Rwpickflavor directory, creates a new 0.1.0 tag, and pushes you every thing to your remote repository. Congratulations, you've created your first cocoapod!






You've created the first cocoapod, but can you really use it? Can not be used very quickly.



You first need to add your podspec to the private specs repo, and when you try to install it this lets cocoapods discover the pod. For this you have created a git repo, so this last step is relatively straightforward.



Enter the following command at the terminal to make sure that you are still in the Rwpickflavor directory.


pod repo add RWPodSpecs [Your RWPodSpecs Git URL]
pod repo push RWPodSpecs RWPickFlavor.podspec


This will create a local reference rwpodspecs on your machine and push the rwpickflavor.podspec onto it.



You now have a private pod specs repo is built! It's easier than you think, right?


Use your new cocoapod


Finally, use the pod you created. For Icecreamshop Open Podfile, enter the following command:


platform :ios, ‘8.0‘
source ‘https://github.com/CocoaPods/Specs.git‘
source ‘[Your RWPodSpecs Git URL Goes Here]‘
use_frameworks!
target ‘IceCreamShop‘ do
  pod ‘RWPickFlavor‘, :path => ‘~/Documents/Libraries/RWPickFlavor‘
end


Make sure you replace the [Your rwpodspecs Git url Goes here]git URL is your rwpodspecs repo, and then run pod install at the terminal.



Finally, replace the Appdelegate.swift with the following.


import UIKit
import RWPickFlavor
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  var rootViewController: UIViewController!
  func application(application: UIApplication, didFinishLaunchingWithOptions 
    launchOptions: [NSObject : AnyObject]?) -> Bool { 
    setupRootViewController()
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.rootViewController = rootViewController
    window?.makeKeyAndVisible()
 
    return true
  } 
  func setupRootViewController() {
    let bundle = NSBundle(forClass: PickFlavorViewController.self)
    let storyboard = UIStoryboard(name: "Main", bundle: bundle)
    rootViewController = storyboard.instantiateInitialViewController() as! UIViewController
  }
}


In Setuprootviewcontroller (), you get a reference to the Rwpickflavor "bundle", which is actually a dynamic binding framework that creates a main.storyboard and instantiates its root view controller.



Build and run. You will see the "Choose Your Flavor" interface you are familiar with.





Abstract All things


If you're like me, you might think, "Wow, App delegate must know a lot about the rwpickflavor structure." Fortunately, there are some things you can do to reduce this coupling, by betterbaseclasses to make it easier to create cocoapods.



Add code to take your Rwpickflavor:


Pod ' betterbaseclasses ', ' ~> 1.0 '


Also add to Rwpickflavor.podspec:


S.dependency ' betterbaseclasses ', ' ~> 1.0 '


Replace version now:


S.version = "0.2.0"


Here, you declare betterbaseclasses as a relationship and then join your cocoapod. Now you install this new dependency on the terminal running pod installs. Next Add extract Pickflavorviewcontroller:


Import betterbaseclasses


Then replace the definition of the class:


public class Pickflavorviewcontroller:baseviewcontroller, uicollectionviewdelegate {


This pickflavorviewcontroller is part of the Baseviewcontroller in betterbaseclasses and now you need to push these changes to your Rwpickflavor andrwpodspecs warehouse. Run the following command:


import UIKit
import RWPickFlavor
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  var rootViewController: UIViewController!
  func application(application: UIApplication, didFinishLaunchingWithOptions 
    launchOptions: [NSObject : AnyObject]?) -> Bool { 
    setupRootViewController()
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.rootViewController = rootViewController
    window?.makeKeyAndVisible()
 
    return true
  } 
  func setupRootViewController() {
    let bundle = NSBundle(forClass: PickFlavorViewController.self)
    let storyboard = UIStoryboard(name: "Main", bundle: bundle)
    rootViewController = storyboard.instantiateInitialViewController() as! UIViewController
  }
}


Next you need to submit these changes to your icecreamshop. Update Icecreamshop podfile, replace ' pod ' rwpickflavor '.


Pod ' Rwpickflavor ', ' ~> 0.2.0


The version of the update Podfile request here is the one you just pushed.



Perform pod install at terminal to update this dependency on Icecreamshop. Finally replace the Appdelegate.swift with the following:


import UIKit
import RWPickFlavor
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  func application(application: UIApplication, didFinishLaunchingWithOptions 
    launchOptions: [NSObject : AnyObject]?) -> Bool { 
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.rootViewController = UINavigationController(rootViewController: 
      PickFlavorViewController.instanceFromStoryboard())
    window?.makeKeyAndVisible()
    return true
  }
}


This is simple, betterbaseclasses added to the U Iviewcontroller, Uitableviewcontroller, and other Uikit classes. This includes a uiviewcontroller+betterbaseclasses that adds a more convenient method, especially Instancefromstoryboard (), which makes it easier to instantiate a view controller. No matter where they live in the main bundle, there are other places, especially in the framework.



Once again build and run, you should see the familiar interface "Choose Your Flavor".


whither?


You can complete the download of Icecreamshop project and the Rwpickflavor Pod project here and here.



You're going to start making your own cocoapods!. However, this tutorial talks about the tip of cocoapods knowledge. You can learn the knowledge of creating CocoaPods by learning CocoaPods guides.









iOS development tutorial: How to create a cocoapod in Swift?


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.