IOS开发入门创建和发布iOS framework
白羽 2019-05-21 来源 :网络 阅读 480 评论 0

摘要:本文将带你了解IOS开发入门创建和发布iOS framework,希望本文对大家学IOS有所帮助。

    本文将带你了解IOS开发入门创建和发布iOS framework,希望本文对大家学IOS有所帮助。


IOS开发入门创建和发布iOS framework


Update note:This  tutorial has been updated to Xcode 8, Cocoapods 1.0, iOS 10 and Swift 3 on  Sept 28, 2016.
   文章包括framework的创建和发布,及其如何对生成的framework进行单元测试;
   CocoaPod的创建和使用,以及如何发布Pod到GitHub。
   原文:点击打开链接
   Have you ever wanted to share a chunk of code between two or more of your  apps, or wanted to share a part of your program with other developers?
   Maybe you wanted to modularize your code similarly to how the iOS SDK  separates its API by functionality, or perhaps you want to distribute your  code in the same way as popular 3rd parties do.
   In this iOS frameworks tutorial you’ll learn how to do all of the  above!
   In iOS 8 and Xcode 6, Apple provided a new template,Cocoa Touch Framework.  As you’ll see, it makes creating custom frameworks much easier than  before.
   Frameworks have three major purposes:
   
   Code encapsulation
   Code modularity
   Code reuse
   
   You can share your framework with your other apps, team members, or the iOS  community. When combined with Swift’s access control, frameworks help define  strong, testable interfaces between code modules.
   In Swift parlance, amoduleis a compiled group of code that is distributed  together. A framework is one type of module, and an app is another  example.
   In this iOS frameworks tutorial, you’ll extract a piece of an existing app  and set it free, and by doing so, you’ll learn the ins and outs of frameworks  by:
   
   Creating a new framework for the rings widget
   Migrating the existing code and tests
   Importing the whole thing back into the app.
   Packing it up as an uber-portable CocoaPods
   Bonus: Setting up a repository for your framework
   
   By the time you’re done, the app will behave exactly as it did before, but  it will use the portable framework you developed! :]
   Getting Started
   Download thePhonercise Starter Project.
   Phonerciseis a simple application that replicates the Apple Watch Activity  app, except it measures your phone’s physical activity. The three rings on  the main view represent movement, standing and exercise.
   To get the most out of the project, you’ll need to build and run on an  actual iOS device, and turn on the volume. Go ahead now, build and run!
   
   Move the phone around to get credit for movement, and “exercise” the phone  by shaking it vigorously — that’ll get its heartrate up. To get credit for  standing up, just hold the phone upright.
   The logic for the app is pretty simple:
   
   ActionViewController.swiftcontains the view lifecycle and motion  logic.
   All the view logic is in the files in theThree Ring Viewfolder, where  you’ll findThreeRingView.swift, which handles the view, andFanfare.swift,  which handles the audio. The other files handle the custom drawing of the  shading, gradient and shapes.
   
   The ring controls are pretty sweet. They’ve got an addictive quality and  they’re easy to understand. Wouldn’t it be nice to use them in a number of  applications beyond this fun, but completely silly app? Frameworks to the  rescue!
   Creating a Framework
   Frameworks are self-contained, reusable chunks of code and resources that  you can import into any number of apps and even share across iOS, tvOS,  watchOS, and macOS apps.
   If you’ve programmed in other languages, you may have heard of node  modules, packages, gems, jars, etc. Frameworks are the Xcode version of  these. Some examples of common frameworks in the iOS SDK  are:Foundation,UIKit,AVFoundation,CloudKit, etc.
   Framework Set Up
   In Xcode 6, Apple introduced theCocoa Touch Frameworktemplate along  withaccess control, so creating frameworks has never been easier. The first  thing to do is to create the project for the framework.
   
   Create a new project. In Xcode, go toFile/New/Project.
   ChooseiOS/Framework & Library/Cocoa Touch Frameworkto create a new  framework.
   
   
   
   ClickNext.
   Set theProduct NametoThreeRingControl. Use your ownOrganization  NameandOrganization Identifier. CheckInclude Unit Tests. That’s right! You’re  going to have automated tests ensure your framework is bug free.
   
   
   
   ClickNext.
   In the file chooser, choose to create the project at the same level as  thePhonerciseproject.
   
   
   
   ClickCreate.
   
   Now you have a project (albeit a boring one) that creates a  framework!
   Add Code and Resources
   Your current state is a framework without code, and that is about as  appealing as straight chocolate without sugar. In this section, you’ll put  the pod in CocoaPods by adding the existing files to the framework.
   From thePhonercisesource directory, drag the following eight files into  theThreeRingControlproject in Xcode:
   
   CircularGradient.swift
   coin07.mp3
   Fanfare.swift
   RingLayer.swift
   RingTip.swift
   ThreeRingView.swift
   Utilities.swift
   winning.mp3
   
   
   Make sure to checkCopy items if needed, so that the files actually copy  into the new project instead of just adding a reference. Frameworks need  their own code, not references, to be independent.
   Double-check that each of the files hasTarget  MembershipinThreeRingControlto make sure they appear in the final framework.  You can see this in theFile Inspectorfor each file.
   
   Build the framework project to make sure that you getBuild Succeededwith no  build warnings or errors.
   Add the Framework to the Project
   Close theThreeRingControlproject, and go back to thePhonerciseproject.  Delete the six files under theThree Ring Viewgroup as well as the two MP3  files inHelper Files. SelectMove to Trashin the confirmation dialog.
   
   Build the project, and you’ll see several predictable errors where Xcode  complains about not knowing what the heck aThreeRingViewis. Well, you’ll  actually see messages along the lines of “Use of undeclared type 'ThreeRingView'“,  among others.
   Adding the Three Ring Control framework project to the workspace is the  solution to these problems.
   Add the Framework to the Project
   Right-click on the rootPhonercisenode in the project navigator. ClickAdd Files  to “Phonercise”. In the file chooser, navigate to and  selectThreeRingControl.xcodeproj. This will addThreeRingControl.xcodeprojas a  sub-project.
   Note:It isn’t strictly necessary to add the framework project to the app  project; you could just add theThreeRingControl.frameworkoutput.
   However, combining the projects makes it easier to develop both the  framework and app simultaneously. Any changes you make to the framework  project are automatically propagated up to the app. It also makes it easier  for Xcode to resolve the paths and know when to rebuild the project.
   Even though the two projects are now together in the  workspace,Phonercisestill doesn’t getThreeRingControl. It’s like they’re  sitting in the same room, but Phonercise can’t see the new framework.
   Try linking the framework to the app’s target to fix this problem. First,  expand theThreeRingControlproject to see theProductsfolder, and then look for  forThreeRingControl.frameworkbeneath it. This file is the output of the  framework project that packages up the binary code, headers, resources and  metadata.
   Select the top levelPhonercisenode to open the project editor. Click  thePhonercisetarget, and then go to theGeneraltab.
   Scroll down to theEmbedded Binariessection.  DragThreeRingControl.frameworkfrom theProductsfolder  ofThreeRingControl.xcodeprojonto this section.
   You just added an entry for the framework in bothEmbedded BinariesandLinked  Frameworks and Binaries.
   
   Now the app knows about the framework and where to find it, so that should  be enough, right?
   Build thePhonerciseproject. More of the same errors.
   
   Access Control
   Your problem is that although the framework is part of the project, the  project’s code doesn’t know about it — out of sight, out of mind.
   Go toActionViewController.swift, and add the following line to the list of  imports at the top of the file.
   
   
   
   
    ?1import ThreeRingControl
   
   
   
   
   It’s critical, but this inclusion won’t fix the build errors. This is  because Swift usesaccess controlto let you determine whether constructs are  visible to other files or modules.
   By default, Swift makes everythinginternalor visible only within its own  module.
   To restore functionality to the app, you have to update the access control  on twoPhonerciseclasses.
   Although it’s a bit tedious, the process of updating access control  improves modularity by hiding code not meant to appear outside the framework.  You do this by leaving certain functions with no access modifier, or by  explicitly declaring theminternal.
   Swift has three levels of access control. Use the following rules of thumb  when creating your own frameworks:
   
   Public: for code called by the app or other frameworks, e.g., a custom  view.
   Internal: for code used between functions and classes within the framework,  e.g., custom layers in that view.
   Fileprivate: for code used within a single file, e.g., a helper function  that computes layout heights.
   Private: for code used within an enclosing declaration, such as a  singleclassblock.Privatecode will not be visible to other blocks, such as  extensions of that class, even in the same file, e.g., private variables,  setters, or helper sub-functions.
   
   Ultimately, making frameworks is so much easier than in the past, thanks to  the new Cocoa Touch Framework template. Apple provided both of these in Xcode  6 and iOS 8.
   Update the Code
   WhenThreeRingView.swiftwas part of the Phonercise app, internal access  wasn’t a problem. Now that it’s in a separate module, it must be  madepublicfor the app to use it. The same is true of the code inFanfare.swift.
   OpenThreeRingView.swiftinside ofThreeRingControlProject.
   Make the class public by adding thepublickeyword to the class definition,  like so:
   
   
   
   
    ?1public class ThreeRingView : UIView {
   
   
   
   
   ThreeRingViewwill now be visible to any app file that imports  theThreeRingControlframework.
   Add thepublickeyword to:
   
   Bothinitfunctions
   The variablesRingCompletedNotification,AllRingsCompletedNotification,layoutSubviews()
   Everything marked@IBInspectable— there will be nine of these
   
   Note: You might wonder why you have to declareinitsas public. Apple  explains this and other finer points of access control in theirAccess Control  Documentation.
   The next step is to do essentially the same thing as you did  forThreeRingView.swift, and add thepublickeyword to the appropriate parts  ofFanfare.swift. For your convenience, this is already done.
   Note that the following variables are public:ringSound,allRingSound,  andsharedInstance. The functionplaySoundsWhenReady()is public as well.
   Now build and run. The good news is that the errors are gone, and the bad  news is that you’ve got a big, white square. Not a ring in sight. Oh no!  What’s going on?
   
   Update the Storyboard
   When using storyboards, references to custom classes need to have both the  class name and module set in theIdentity Inspector. At the time of this  storyboard’s creation,ThreeRingViewwas in the app’s module, but now it’s in  the framework.
   Update the storyboard, as explained below, by telling it where to find the  custom view; this will get rid of the white square.
   
   OpenMain.Storyboardin thePhonerciseproject.
   Select theRing Controlin the view hierarchy.
   In theIdentity Inspector, underCustom Class, change  theModuletoThreeRingControl.
   
   Once you set the module, Interface Builder should update and show the  control in the editor area.
   
   Build and run. Now you’ll get some rings.
   
   Update the Tests
   There’s one final place to update before you can actually use the  framework. It’s the oft-forgotten test suite. :]
   This app includes unit tests. However, the tests have a dependency  onThreeRingControl, so you need to fix that.
   Note:Before Swift 2.0, unit testing was difficult, but Swift 2.0 came along  with@testable, making testing far easier. It means you no longer have to make  all your project’s items public just to be able to test them.
   Simply import the module you want to test using the@testablekeyword, and  your test target will have access to all internal routines in the imported  module.
   The first test isThreeRingTest.swift, which tests functionality  withinThreeRingView.swiftand should be part of  theThreeRingControlframework.
   From thePhonerciseTestsgroup in the app project, dragThreeRingTest.swiftto  theThreeRingControlTestsgroup in the framework project.
   SelectCopy items if needed, and make sure you select  theThreeRingControlTeststarget and not the framework target.
   
   Then delete theThreeRingTest.swiftfrom the app project. Move it to the  trash.
   Open the copied test file, and change the import line from:
   
   
   
   
    ?1@testable import Phonercise
   
   
   
   
   To:
   
   
   
   
    ?1import ThreeRingControl
   
   
   
   
   Click therun testbutton in the editor’s gutter, and you’ll see a green  checkmark showing that the test succeeded.
   
   This test doesn’t need@testablein its import since it is only  callingpublicmethods and variables.
   The remaining app test doesn’t work this way though. Go back the to  thePhonercisetarget and openPhonerciseTests.swift.
   Add the following import to the existing imports at the top:
   
   
   
   
    ?1import ThreeRingControl
   
   
   
   
   Now run thePhonerciseTeststests. The particular test should execute and  pass.
   Congratulations. You now have a working stand-alone framework and an app  that uses it!
   
   Creating a CocoaPod
   CocoaPodsis a popular dependency manager for iOS projects. It’s a tool for  managing and versioning dependencies. Similar to a framework, a CocoaPod, or  ‘pod’ for short, contains code, resources, etc., as well as metadata,  dependencies, and set up for libraries. In fact, CocoaPods are built as  frameworks that are included in the main app.
   Anyone can contribute libraries and frameworks to the public repository,  which is open to other iOS app developers. Almost all of the popular  third-party frameworks, such as Alamofire, React native and SDWebImage,  distribute their code as a pod.
   Here’s why you should care: by making a framework into a pod, you give  yourself a mechanism for distributing the code, resolving the dependencies,  including and building the framework source, and easily sharing it with your  organization or the wider development community.
   Clean out the Project
   Perform the following steps to remove the current link  toThreeRingControl.
   
   SelectThreeRingControl.xcodeprojin the project navigator and delete  it.
   ChooseRemove Referencein the confirmation dialog, since you’ll need to keep  the files on disk to create the pod.
   
   Install CocoaPods
   If you’ve never used CocoaPods before, you’ll need to follow a brief installation  process before going any further. Go to theCocoaPods Installation Guideand  come back here when you’re finished. Don’t worry, we’ll wait!
   Create the Pod
   Open Terminal in theThreeRingControldirectory.
   Run the following command:
   
   
   
   
    ?1pod spec create ThreeRingControl
   
   
   
   
   This creates the fileThreeRingControl.podspecin the current directory. It’s  a template that describes the pod and how to build it. Open it in a text  editor.
   The template contains plenty of comment descriptions and suggestions for  the commonly used settings.
   
   Replace theSpec Metadatasection with: s.name =  "ThreeRingControl"
   s.version = "1.0.0"
   s.summary = "A three-ring control like the Activity status  bars"
   s.description = "The three-ring is a completely customizable widget  that can be used in any iOS app. It also plays a little victory  fanfare."
   s.homepage = "//raywenderlich.com"
   
   
   
   
    ?1 
   
   
   
   
   Normally, the description would be a little more descriptive, and the  homepage would point to a project page for the framework.
   
   Replace theSpec Licensesection with the below code, as this iOS frameworks  tutorial code uses anMIT License: s.license = "MIT"
   
   
   
   
    ?1 
   
   
   
   
   
   You can keep theAuthor Metadatasection as is, or set it u with how you’d  lke to be credited and contacted.
   Replace thePlatform Specificssection with the below code, because this is  an iOS-only framework.: s.platform = :ios, "10.0"
   
   
   
   
    ?1 
   
   
   
   
   
   Replace theSource Locationwith the below code. When you’re ready to share  the pod, this will be a link to the GitHub repository and the commit tag for  this version. s.source = { :path => '.' }
   
   
   
   
    ?1 
   
   
   
   
   
   Replace theSource Codesection with: s.source_files =  "ThreeRingControl", "ThreeRingControl/**/*.{h,m,swift}"  
   
   
   
   
    ?1 
   
   
   
   
   
   And theResourcessection with: s.resources =  "ThreeRingControl/*.mp3"
   
   
   
   
    ?1 
   
   
   
   
   This will include the audio resources into the pod’s framework  bundle.
   
   Remove theProject LinkingandProject Settingssections.
   Add the following line. This line helps the application project understand  that this pod’s code was written for Swift 3. s.pod_target_xcconfig = {  'SWIFT_VERSION' => '3' }
   
   
   
   
    ?1 
   
   
   
   
   
   Remove all the remaining comments — the lines that start with#.
   
   You now have a workable development Podspec.
   Note:If you runpod spec lintto verify thePodspecin Terminal, it’ll show an  error because thesourcewas not set to a valid URL. If you push the project to  GitHub and fix that link, it will pass. However, having the linter pass is  not necessary for local pod development. ThePublish the Podsection below  covers this.
   Use the Pod
   At this point, you’ve got a pod ready to rock and roll. Test it out by  implementing it in thePhonerciseapp.
   Back in Terminal, navigate up to thePhonercisedirectory, and then run the  following command:
   
   
   
   
    ?1pod init
   
   
   
   
   This steathily creates a new file namedPodfilethat lists all pods that the  app uses, along with their versions and optional configuration  information.
   OpenPodfilein a text editor.
   Next, add the following line under the comment,# Pods for Phonercise:
   pod 'ThreeRingControl', :path => '../ThreeRingControl'
   
   
   
   
    ?1 
   
   
   
   
   Save the file.
   Run this in Terminal:
   pod install
   
   
   
   
    ?1 
   
   
   
   
   With this command, you’re searching the CocoaPods repository and  downloading any new or updated pods that match the Podfile criteria. It also  resolves any dependencies, updates the Xcode project files so it knows how to  build and link the pods, and performs any other required configuration.
   Finally, it creates aPhonercise.xcworkspacefile. Use this file from now on  — instead of thexcodeproj— because it has the reference to the Pods project  and the app project.
   Check it Out
   Close thePhonerciseandThreeRingControlprojects if they are open, and then  openPhonercise.xcworkspace.
   Build and run. Like magic, the app should work exactly the same before.  This ease of use is brought to you by these two facts:
   
   You already did the work to separate theThreeRingControlfiles and use them  as a framework, e.g. adding import statements.
   CocoaPods does the heavy lifting of building and packaging those files; it  also takes care of all the business around embedding and linking.
   
   Pod Organization
   Take a look at thePodsproject, and you’ll notice two targets:
   
   
   Pods-phonercise: a pod project builds all the inpidual pods as their own  framework, and then combines them into one single  framework:Pods-Phonercise.
   ThreeRingControl: this replicates the same framework logic used for  building it on its own. It even adds the music files as framework resources.  
   
   Inside the project organizer, you’ll see several groups.ThreeRingControlis  underDevelopment Pods. This is adevelopment podbecause you defined the pod  with:pathlink in the app’sPodfile. These files are symlinked, so you can edit  and develop this code side-by-side with the main app code.
   
   Pods that come from a repository, such as those from a third party, are  copied into thePodsdirectory and listed in aPodsgroup. Any modifications you  make are not pushed to the repository and are overwritten whenever you update  the pods.
   Congratulations! You’ve now created and deployed a CocoaPod — and you’re  probably thinking about what to pack into a pod first.
   You’re welcome to stop here, congratulate yourself and move on toWhere to  Go From Here, but if you do, you’ll miss out on learning an advanced  maneuver.
   Publish the Pod
   This section walks you through the natural next step of publishing the pod  to GitHub and using it like a third party framework.
   Create a Repository
   If you don’t already have a GitHub account,create one.
   Now create a new repository to host the pod.ThreeRingControlis the obvious  best fit for the name, but you can name it whatever you want. Be sure to  selectSwiftas the.gitignorelanguage andMITas the license.
   
   ClickCreate Repository. From the dashboard page that follows, copy  theHTTPSlink.
   Clone the Repository
   Go back to Terminal and create a new directory. The following commands will  create arepodirectory from the project’s folder.
   mkdir repo
   cd repo
   
   
   
   
    ?1 
   
   
   
   
   From there,clonethe GitHub repository. Replace theURLbelow with  theHTTPSlink from the GitHub page.
   git clone URL
   
   
   
   
    ?1 
   
   
   
   
   This will set up a Git folder and go on to copy the  pre-createdREADMEandLICENSEfiles.
   
   Add the Code to the Repository
   Next, copy the files from the previousThreeRingControldirectory to  therepo/ThreeRingControldirectory.
   Open the copied version ofThreeRingControl.podspec, and update  thes.sourceline to:
   s.source = { :git => "URL", :tag => "1.0.0" }  
   
   
   
   
    ?1 
   
   
   
   
   Set theURLto be the link to your repository.
   Make the Commitment
   Now it gets real. In this step, you’ll commit and push the code to GitHub.  Your little pod is about to enter the big kid’s pool.
   Run the following commands in Terminal to commit those files to the  repository and push them back to the server.
   cd ThreeRingControl/
   git add .
   git commit -m "initial commit"
   git push
   
   
   
   
    ?1 
   
   
   
   
   Visit the GitHub page and refresh it to see all the files.
   
   Tag It
   You need to tag the repository so it matches the Podspec. Run this command  to set the tags:
   git tag 1.0.0git push --tags
   
   
   
   
    ?1 
   
   
   
   
   Check your handiwork by running:
   
   
   
   
    ?1pod spec lint
   
   
   
   
   The response you’re looking for isThreeRingControl.podspec passed  validation.
   Update the Podfile
   Change thePodfilein thePhonercisedirectory. Replace the existingThreeRingControlline  with:
   pod 'ThreeRingControl', :git => 'URL', :tag => '1.0.0'

   
   ReplaceURLwith your GitHub link.
   From Terminal, run this in thePhonercisedirectory:

   
 1pod update
   

   Now the code will pull the framework from the GitHub repository, and it is  no longer be a development pod!
   
   Where to Go From Here?
   In this iOS frameworks tutorial, you’ve made a framework from scratch that  contains code and resources, you’ve reimported that framework back into your  app, and even turned it into a CocoaPod. Nice work!
   You can download the final project
   <a  data-cke-saved-href="https://koenig-media.raywenderlich.com/uploads/2016/06/Phonercise-Final.zip"  href="https://koenig-media.raywenderlich.com/uploads/2016/06/Phonercise-Final.zip"  "="" style="border: 0px; font-family: inherit;  font-style: inherit; font-weight: inherit; margin: 0px; outline: 0px;  padding: 0px; vertical-align: baseline; color: rgb(0, 104, 55);">  Hats off to Sam Davies for developing theThreeRingControl. You might remember  him from such videos asIntroducing Custom Controls, where you can learn more  about custom controls and custom frameworks.
   The team here has put together a lot of tutorials about CocoaPods, and now  that you’ve gone through a crash course, you’re ready to learn more. Here are  a couple that you might like:
   
   How to Use CocoaPods with Swift
   How to create a CocoaPod in Swift
   
   Spend some time atCocoaPods.organd be sure to check out how to submit to  the public pod repository and the dozens of configuration flags.
   What did you learn from this? Any lingering questions? Want to share  something that happened along the way? Let’s talk about it in the forums. See  you there!   


本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之IOS频道!

本文由 @白羽 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程