Delete Afnetworking From Thridparty and Use Pod to Install Again
Update note: Rony Rozen updated this tutorial for Xcode xi and Swift 5. Joshua Greene wrote the original.
CocoaPods is a popular dependency manager for Swift and Objective-C Cocoa projects. Thousands of libraries and millions of apps utilise information technology, according to the CocoaPods website. But what is a dependency manager and why exercise you need 1?
A dependency director makes it easy to add, remove, update and manage the third-party dependencies your app uses.
For example, instead of reinventing your own networking library, you lot can easily pull in Alamofire using a dependency manager. You lot can specify either the exact version to use or a range of acceptable versions.
This means that even if Alamofire gets an update with changes that aren't astern-compatible, your app can continue using the older version until you're set to update it.
In this tutorial, you'll acquire how to employ CocoaPods with Swift. Specifically, you'll:
- Install CocoaPods.
- Work with a functional demo app that gets yous thinking about water ice cream.
- Use CocoaPods to add together networking.
- Learn almost semantic versioning.
- Add some other library using a flexible version.
Annotation: This CocoaPods tutorial requires basic familiarity with iOS and Swift development. If you lot're completely new to iOS and/or Swift, and then please check out some of the other written and/or video tutorials on this site before doing this tutorial. Or, dive into our book, iOS Apprentice.
This tutorial besides includes classes that use Core Graphics. While knowledge of Core Graphics is benign, it's not required. If yous'd like to learn more, read our Modern Core Graphics With Swift series.
Getting Started
Download the starter project by clicking the Download Materials push button at the top or bottom of the tutorial.
Throughout this tutorial, you lot'll work with an app called Water ice Cream Store, Inc. You'll use CocoaPods to add dependencies to the app the easy mode, instead of writing your ain.
Before you tin continue with this tutorial, you need to install CocoaPods. Fortunately, CocoaPods uses Ruby, which ships with all versions of macOS Ten since version 10.7.
Open Last and enter the following command:
sudo jewel install cocoapods Enter your password when requested. The Last output volition show various fetching, installing and documentation-related outputs, terminal with "Twenty gems installed".
Notation: You lot must use sudo to install CocoaPods, but once it's installed, you won't need to utilise it again in this tutorial.
Finally, enter this command in Concluding to complete the setup:
pod setup --verbose This process takes a few minutes because it clones the CocoaPods Master Specs repository into ~/.cocoapods/ on your computer.
The verbose option logs progress as the procedure runs, allowing you lot to watch the process instead of seeing a seemingly "frozen" screen.
Awesome, y'all're now set upwards to utilize CocoaPods!
Ice Cream Shop, Inc.
Your top client is Ice Foam Store, Inc. Their ice cream is so pop they tin can't go on upward with client orders at the counter. They've recruited yous to create a sleek iOS app that allows customers to order water ice foam correct from their iPhones.
Y'all've started developing the app and it's coming along well. Take a look at your progress by opening IceCreamShop.xcodeproj, then edifice and running. You lot'll see a oral cavity-watering vanilla ice cream cone:
The user should be able to choose an ice cream flavor from this screen, but that's not possible yet. Your outset step is to stop implementing this functionality.
Open up Principal.storyboard from the Views/Storyboards & Nibs grouping to run into the app's layout. Here'south a quick overview of the heart of the app, the Choose Your Flavor scene:
-
PickFlavorViewControlleris the view controller for this scene. It handles user interaction and provides the data for the collection view that displays the different water ice cream flavors. -
IceCreamViewis a custom view that displays an ice cream cone based on the backing mode,Flavour. -
ScoopCellis a custom collection view cell that contains aScoopView, which gets colors from aFlavormodel.
While every Water ice Cream Store, Inc. location has signature flavors in common, each carries its own local flavors, too. For this reason, a web service needs to provide the data for the Seasons.
Withal, this notwithstanding doesn't explain why users can't select their ice cream flavors.
Open up PickFlavorViewController.swift, institute under the Controllers grouping, and you'll see a stubbed method:
private func loadFlavors() { // TO-DO: Implement this } Aha, in that location are no flavors! You need to implement the function!
While you could employ URLSession and write your own networking classes, there'southward an easier fashion: Use Alamofire!
You might be tempted to download this library and elevate the source files right into your project. Notwithstanding, that'd be doing it the hard manner. CocoaPods provides a much more elegant and nimble solution.
Installing Your First Dependency
Your first step is to close Xcode. Yep, you read that right.
It's time to create the Podfile, where you lot'll ascertain your project's dependencies.
Open Terminal and navigate to the directory that contains your IceCreamShop project by using the cd command:
cd ~/Path/To/Folder/Containing/IceCreamShop Next, enter the following command:
pod init This creates a Podfile for your projection.
Finally, type the post-obit command to open the Podfile using Xcode for editing:
open up -a Xcode Podfile Note: Don't utilize TextEdit to edit the Podfile because information technology replaces standard quotes with more graphically-highly-seasoned typeset quotes. This tin cause CocoaPods to become confused and throw errors. Instead, use Xcode or another programming text editor to edit your Podfile.
The default Podfile looks like this:
# Uncomment the next line to define a global platform for your project # platform :ios, 'nine.0' target 'IceCreamShop' do # Comment the side by side line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for IceCreamShop end Delete the # and infinite before platform, then delete the other lines starting with #.
Your Podfile should now look similar this:
platform :ios, '9.0' target 'IceCreamShop' exercise use_frameworks! finish This tells CocoaPods your project targets iOS 9.0 and will employ frameworks instead of static libraries. While Swift and CocoaPods both back up static linking, not all libraries yous include do. One of them that you'll apply in this project does non.
If you've only programmed in Swift, this may look a bit strange. That's considering the Podfile is actually written in Cherry. You lot don't need to know Ruby to use CocoaPods, but you should exist enlightened that even minor text errors volition cause CocoaPods to throw errors.
A Word Almost Libraries
Yous'll see the term library often used as a general term that actually means a library or framework. This tutorial is guilty of casually intermixing these words, too.
You may exist wondering about the differences betwixt a library, a framework and a CocoaPod. It's OK if you lot detect the terminology a chip confusing!
A CocoaPod, or pod for short, is a general term for either a library or framework that'southward added to your project using CocoaPods.
iOS eight introduced dynamic frameworks, which allow you lot to packet code, images and other avails together. Prior to iOS 8, you created CocoaPods as "fat" static libraries. "Fat" means they contained several lawmaking instruction sets, like i386 for the simulator, armv7 for devices, etc. However, Swift doesn't allow static libraries to contain resource such as images or assets.
Back to Installing Your First Dependency
It's finally time to add your starting time dependency using CocoaPods. Add together the post-obit to your Podfile, right after use_frameworks!:
pod 'Alamofire', '4.ix.1' This tells CocoaPods you want to include Alamofire version 4.ix.1 equally a dependency for your project.
Salvage and close the Podfile.
Y'all now need to tell CocoaPods to install the dependencies for your project.
Enter the post-obit command in Terminal, after ensuring you're still in the directory containing the IceCreamShop project and Podfile:
pod install You should encounter output like this:
Analyzing dependencies Calculation spec repo `body` with CDN `https://cdn.cocoapods.org/` Downloading dependencies Installing Alamofire (4.nine.1) Generating Pods project Integrating client project [!] Please close any current Xcode sessions and use `IceCreamShop.xcworkspace` for this project from now on. Pod installation complete! There is 1 dependency from the Podfile and ane total pod installed. Open the project folder using Finder and y'all'll come across CocoaPods created a new IceCreamShop.xcworkspace file and a Pods folder to store all the project'due south dependencies.
Note: From now on, as the command line alarm mentioned, you lot must always open up the project with the .xcworkspace file and non the .xcodeproj. Otherwise, y'all'll encounter build errors.
Excellent! Y'all've just added your showtime dependency using CocoaPods!
Using Installed Pods
At present, you'll apply your brand new dependency, Alamofire.
If the Xcode project is open up, shut it now and open IceCreamShop.xcworkspace.
Open PickFlavorViewController.swift and add the following just below the existing import:
import Alamofire Build and run. You lot'll see no change yet just rest assured that Alamofire is now available.
Next, supercede loadFlavors() with the following:
private func loadFlavors() { // 1 Alamofire.request( "https://world wide web.raywenderlich.com/downloads/Flavors.plist", method: .get, encoding: PropertyListEncoding(format: .xml, options: 0)) .responsePropertyList { [weak self] response in // 2 guard let self = self else { render } // iii guard response.result.isSuccess, let dictionaryArray = response.result.value as? [[String: String]] else { render } // 4 self.flavors = self.flavorFactory.flavors(from: dictionaryArray) // 5 self.collectionView.reloadData() self.selectFirstFlavor() } } Here's the play-by-play of what's happening in this code:
- Yous use Alamofire to create a Go asking and download a plist containing water ice cream flavors.
- To break a strong reference wheel, you use a weak reference to
selfin the response completion block. Once the block executes, you immediately go a strong reference toselfthen yous can set properties on it afterwards. - Next, yous verify the
response.resultshows success and theresponse.result.valueis an array of dictionaries. - Now, you lot set
cocky.flavorsto an array ofFlavorobjects thatFlavorFactorycreates. This is a class a "colleague" wrote for y'all (yous're welcome!), which takes an array of dictionaries and uses them to create instances ofFlavor. - Finally, you reload the collection view and select the starting time flavor.
Build and run. You lot can now choose an water ice cream flavor!
Now for a Tasty Topping
The app looks proficient, but you can even so amend it.
Did you notice the app takes a 2nd to download the flavors file? If you're on a fast Internet connection, you might not notice the delay, but your customers won't always be and so lucky.
Your adjacent step is to evidence a loading indicator in your app, to help customers sympathize it's loading data and not just twiddling its libraries. MBProgressHUD is a actually nice indicator that will work well here. And information technology supports CocoaPods; what a coincidence! :]
To use this pod, you need to add together it to your Podfile. Rather than opening the Podfile from the control line, y'all tin can now find it in the Pods target in the workspace:
Open up Podfile and add together the post-obit, right after the Alamofire line:
pod 'MBProgressHUD', '~> i.0' Salve the file and install the dependencies via pod install in Terminal, only every bit yous did before.
Observe anything different this time? Yep, yous specified the version number equally ~> ane.0. But why?
CocoaPods recommends that all pods utilize Semantic Versioning. Accept a moment to empathize what that is.
Semantic Versioning
Many times, yous'll see a version written similar this: 1.0.0. Those 3 numbers are major, modest and patch version numbers.
For instance, for the version number 1.0.0, ane is the major number, the get-go 0 is the minor number, and the second 0 is the patch number.
If the major number increases, it indicates that the version contains non-backward-compatible changes. When you upgrade a pod to the next major version, you lot may need to ready build errors or the pod may carry differently than before.
If the minor number increases, it indicates that the version contains new functionality that is backward-uniform. When you decide to upgrade, y'all may or may not need the new functionality, but information technology shouldn't cause whatever build errors or alter existing beliefs.
If the patch number increases, it means the new version contains bug fixes but no new functionality or behavior changes. In general, yous always desire to upgrade patch versions as soon every bit possible to take the latest, stable version of the pod.
Finally, when you increase the highest-order number — major, so minor and then patch — per the above rules, you must reset any lower-order numbers to zero.
Hither's an example:
Consider a pod that has a current version number of 1.2.iii.
If you make changes that are not backward-uniform, don't accept new functionality, but fix existing bugs, you'd give information technology version ii.0.0.
Challenge Fourth dimension
If a pod has a electric current version of 2.4.6 and yous make changes that ready bugs and add together backward-compatible functionality, what should the new version number exist?
[spoiler]
Answer: two.five.0
Explanation: If you make changes that include new functionality that's backward-compatible, you increase the minor number and reset the patch to nix.
[/spoiler]
If a pod has a current version of 3.5.8 and you make changes to existing functionality which aren't backward-compatible, what should the new version number exist?
[spoiler]
Respond: four.0.0
Explanation: If changes modify existing beliefs and are non astern-compatible, you must increase the major number and reset the minor and patch numbers to zero.
[/spoiler]
If a pod has a current version of 10.20.30 and y'all only prepare bugs, what should the new version number be?
[spoiler]
Answer: 10.20.31
Explanation: If you lot only prepare bugs, you only increment the patch number.
[/spoiler]
Having said all this, in that location'southward i exception to these rules:
If a pod's version number is less than 1.0.0, information technology'south considered a beta version. Minor number increases may include changes that aren't backward-compatible.
And so back to MBProgressHUB: Using ~> 1.0 means you should install the latest version that'due south greater than or equal to 1.0 just less than ii.0.
This ensures you lot become the latest bug fixes and features when you install this pod, but you won't accidentally pull in astern-incompatible changes.
There are several other operators yous can utilize also. For a consummate list, see the Podfile Syntax Reference.
Now that y'all've learned how operators work with your CocoaPods, information technology's time to finish your app.
Showing Progress
If you recall, you were building a progress indicator to show your users when flavors are loading in the app.
To stop this feature, become dorsum to PickFlavorViewController.swift and add the following right after the other imports:
import MBProgressHUD Next, add together the post-obit helper methods after loadFlavors():
private func showLoadingHUD() { allow hud = MBProgressHUD.showAdded(to: contentView, animated: true) hud.label.text = "Loading..." } private func hideLoadingHUD() { MBProgressHUD.hide(for: contentView, animated: truthful) } At present, in loadFlavors(), add the following ii lines (every bit indicated):
individual func loadFlavors() { showLoadingHUD() // <-- Add this line Alamofire.request( "https://www.raywenderlich.com/downloads/Flavors.plist", method: .get, encoding: PropertyListEncoding(format: .xml, options: 0)) .responsePropertyList { [weak self] response in baby-sit permit self = cocky else { return } cocky.hideLoadingHUD() // <-- Add this line // ... As the method names imply, showLoadingHUD() shows an instance of MBProgressHUD while the GET request downloads. hideLoadingHUD() hides the HUD when the request finishes. Since showLoadingHUD() is outside the closure, it doesn't need the self prefix.
Build and run. You'll at present see a loading indicator while the flavors are loading. If your internet connectedness is too fast for this, you can add a sleep(_:) statement only earlier hideLoadingHUD() and so that you can experience the goodness that is MBProgressHUD. :]
Great work! Customers tin can now select their favorite ice cream flavor and they see a loading indicator while flavors are downloading.
Where to Get From Here?
You lot can download the completed project using the Download Materials push button at the pinnacle or bottom of this folio.
Congratulations! You lot now know the basics of using CocoaPods, including creating and modifying dependencies and understanding semantic versioning. You're now set to start using them in your own projects!
There's lots more that you can exercise with CocoaPods. Y'all can search for existing pods on the official CocoaPods website. Also, refer to the CocoaPods Guides to learn the effectively details of this excellent tool. But be warned, one time you begin using it, you'll wonder how you ever managed without information technology! :]
I hope y'all enjoyed reading this CocoaPods tutorial as much I did writing information technology. What are some of your favorite CocoaPods? Which ones do you rely on the near for everyday projects? Experience complimentary to share, or to enquire any questions, in the comments below!
Source: https://www.raywenderlich.com/7076593-cocoapods-tutorial-for-swift-getting-started
0 Response to "Delete Afnetworking From Thridparty and Use Pod to Install Again"
Post a Comment