Environment to prepare

Update the gem source. If no gems are installed in the system, install the gem environment first

$ sudo gem update --system 
Latest version already installed. Done.
Copy the code

CocoaPods relies on Ruby, so before you start your project, check out your native Ruby environment, which is usually shipped with Macs.

$ gem sources -l
*** CURRENT SOURCES ***
https://rubygems.org/
Copy the code

Because the official Ruby source is blocked, the Ruby source needs to be modified.

$ gem sources --remove https://rubygems.org/
$ gem sources --add https://gems.ruby-china.com/
Copy the code

Check to see if the Ruby image has been switched

$ gem sources -l                        
*** CURRENT SOURCES ***

https://gems.ruby-china.com/
Copy the code

View your local CocoaPods version

$ pod --version              
1.10.1
Copy the code

If not, install CocoaPods first

$ sudo gem install -n /usr/local/bin cocoapods
Copy the code

Look again at the CocoaPods version

$ pod --version              
1.10.1
Copy the code

Tools to prepare

To do a good job, you must sharpen your tools!

Private warehouse preparation

Create a remote private repository. Because the repository name in the example already exists, Gitee will get an error message, but continue.

Add the remote repository to the local Pod Repo

$ pod repo add ishadoo-specs https://gitee.com/ishadoo/Specs.git
Copy the code

Viewing the local repository

$ pod repo list  

ishadoo-specs
- Type: git (master)
- URL:  https://gitee.com/ishadoo/Specs.git
- Path: /Users/wangchuanhai/.cocoapods/repos/ishadoo-specs

master
- Type: git (master)
- URL:  https://github.com/CocoaPods/Specs.git
- Path: /Users/wangchuanhai/.cocoapods/repos/master

trunk
- Type: CDN
- URL:  https://cdn.cocoapods.org/
- Path: /Users/wangchuanhai/.cocoapods/repos/trunk
Copy the code

CHModuleConfig tools

Gitee Warehouse address: gitee.com/ishadoo/CHM…

Initialize the project to associate the iOS project with the remote Git repository.

The Config script:

  • Did 3 things:

    • To start your local iOS project, add a Podspec file.
    • Associate the initialized project with a remote private repository.
    • Add a private library upload script.
#! /bin/bash

Cyan='\033[0;36m'
Default='\033[0;m'

projectName=""
httpsRepo=""
sshRepo=""
homePage=""
confirmed="n"

getProjectName() {
    read -p "Enter Project Name: " projectName
    if test -z "$projectName"; then
        getProjectName
    fi
}

getHTTPSRepo() {
    read -p "Enter HTTPS Repo URL: " httpsRepo
    if test -z "$httpsRepo"; then
        getHTTPSRepo
    fi
}

getSSHRepo() {
    read -p "Enter SSH Repo URL: " sshRepo
    if test -z "$sshRepo"; then
        getSSHRepo
    fi
}

getHomePage() {
    read -p "Enter Home Page URL: " homePage
    if test -z "$homePage"; then
        getHomePage
    fi
}

getInfomation() {
    getProjectName
    getHTTPSRepo
    getSSHRepo
    getHomePage

    echo -e "\n${Default}= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ="
    echo -e "  Project Name  :  ${Cyan}${projectName}${Default}"
    echo -e "  HTTPS Repo    :  ${Cyan}${httpsRepo}${Default}"
    echo -e "  SSH Repo      :  ${Cyan}${sshRepo}${Default}"
    echo -e "  Home Page URL :  ${Cyan}${homePage}${Default}"
    echo -e "================================================\n"
}

echo -e "\n"
while [ "$confirmed"! ="y" -a "$confirmed"! ="Y" ]
do
    if [ "$confirmed"= ="n" -o "$confirmed"= ="N" ]; then
        getInfomation
    fi
    read -p "confirm? (y/n):" confirmed
done

mkdir -p ".. /${projectName}/${projectName}"

licenseFilePath=".. /${projectName}/FILE_LICENSE"
gitignoreFilePath=".. /${projectName}/.gitignore"
specFilePath=".. /${projectName}/${projectName}.podspec"
readmeFilePath=".. /${projectName}/readme.md"
uploadFilePath=".. /${projectName}/upload.sh"
podfilePath=".. /${projectName}/Podfile"

echo "copy to $licenseFilePath"
cp -f ./templates/FILE_LICENSE "$licenseFilePath"
echo "copy to $gitignoreFilePath"
cp -f ./templates/gitignore    "$gitignoreFilePath"
echo "copy to $specFilePath"
cp -f ./templates/pod.podspec  "$specFilePath"
echo "copy to $readmeFilePath"
cp -f ./templates/readme.md    "$readmeFilePath"
echo "copy to $uploadFilePath"
cp -f ./templates/upload.sh    "$uploadFilePath"
echo "copy to $podfilePath"
cp -f ./templates/Podfile      "$podfilePath"

echo "editing..."
sed -i "" "s%__ProjectName__%${projectName}%g" "$gitignoreFilePath"
sed -i "" "s%__ProjectName__%${projectName}%g" "$readmeFilePath"
sed -i "" "s%__ProjectName__%${projectName}%g" "$uploadFilePath"
sed -i "" "s%__ProjectName__%${projectName}%g" "$podfilePath"

sed -i "" "s%__ProjectName__%${projectName}%g" "$specFilePath"
sed -i "" "s%__HomePage__%${homePage}%g"      "$specFilePath"
sed -i "" "s%__HTTPSRepo__%${httpsRepo}%g"    "$specFilePath"
echo "edit finished"

echo "cleaning..."cd .. /$projectName git init git remote add origin $httpsRepo &>/dev/null
git rm -rf --cached ./Pods/     &> /dev/null
git rm --cached Podfile.lock    &> /dev/null
git rm --cached .DS_Store       &> /dev/null
git rm -rf --cached $projectName.xcworkspace/           &> /dev/null
git rm -rf --cached $projectName.xcodeproj/xcuserdata/`whoami`.xcuserdatad/xcschemes/$projectName.xcscheme &> /dev/null
git rm -rf --cached $projectName.xcodeproj/project.xcworkspace/xcuserdata/ &> /dev/null
git add . &> /dev/null
git commit -m "first commit"& >/dev/null
git push -u origin master &> /dev/null
echo "clean finished"
say "finished"
echo "finished"

Copy the code

templates

Provides a configuration file template that initializes uploading to the CocoaPods repository module project.

This template provides basic configuration information.

  • Pod. Podspec template

    Initialize the podspec file of the private library module to initialize the basic configuration for subsequent modules to be uploaded to the private repository.

    Pod::Spec.new do |s|
    
        s.name         = "__ProjectName__"
        s.version      = "1.0.0"
        s.summary      = "__ProjectName__."
        s.description  = <<-DESC this is __ProjectName__ DESC
        s.homepage     = "__HomePage__"
        s.license      = { :type= >"MIT".:file= >"FILE_LICENSE" }
        s.author             = { "Wang Chuanhai"= >"[email protected]" }
        s.platform     = :ios."10.0"
        s.source       = { :git= >"__HTTPSRepo__".:tag => s.version }
        s.source_files  = "__ProjectName__/__ProjectName__/**/*.{h,m}"
        s.requires_arc = true
      
      end
    Copy the code
  • Podfile template

    The initial project’s Podfile file

    # Uncomment this line to define a global platform for your project
    platform :ios, '10.0'
    
    source 'https://gitee.com/ishadoo/Specs.git'
    source 'https://github.com/CocoaPods/Specs.git'
    
    target '__ProjectName__' do
    
    end
    Copy the code
  • Upload Script template

    To initialize the module upload script, you need to change the repo name and private repository address in the file according to the local repo

    pod repo push ishadoo-specs __ProjectName__.podspec --verbose --allow-warnings --use-libraries --sources='https://gitee.com/ishadoo/Specs.git,https://github.com/CocoaPods/Specs.git'
    Copy the code

The project of actual combat

Because of the privacy and security concerns of git repositories, this tutorial uses the Gitee repository as an example to teach you how to build an iOS modular architecture from scratch.

Prepare ModuleConfig

My project path is ~/code/private/CHShare.

$ cd ~/code/private/CHShare
$ git clone https://gitee.com/ishadoo/CHModuleConfig.git
Copy the code

Create the remote project address

The remote repository is chosen according to your project environment, and I used Gitee for the tutorial.

Create an Xcode local project

The project name must be the same as the name of the remote project. When creating a project, directly copy the name of the remote project and set the path to the same level as the ModuleConfig

At this point in the project directory structure we just created the CHShareThird project

Use CHModuleConfig to initialize the project and upload it to the remote repository

The main task of this step is to initialize the local project to be managed by CocoaPods.

Synchronize the project to the Git remote repository at the same time.

CD to the root directory of CHModuleConfig and run the initial configuration script config.sh.

~ » CD/Users/wangchuanhai/code/private/CHShare/CHModuleConfig ------------------------------------------------------------------------------------------------------------------------ -- -- -- -- -- -- -- -- -- - / code/private/CHShare/CHModuleConfig (master *) » ll total 32 - rw - r - r - 1 wangchuanhai staff 1.0 K 3 7 unto them LICENSE -rw-r--r-- 1 wangchuanhai staff 839B 3 7 14:24 README.en.md -rw-r--r-- 1 wangchuanhai staff 928B 3 7 14:24 Readme.md-rwxr-xr-x 1 Wangchuanhai staff 3.2k 3 7 14:04 config. Sh drwxR-xR-x 6 Wangchuanhai staff 192B 3 7 14:06 templates ------------------------------------------------------------------------------------------------------------------------ -- -- -- -- -- -- -- -- -- - / code/private/CHShare CHModuleConfig (master *) ». / config. Sh Enter Project Name: CHShareThird Enter HTTPS Repo URL: https://gitee.com/ishadoo/CHShareThird.git Enter SSH Repo URL: [email protected]:ishadoo/CHShareThird.git Enter Home Page URL: https://gitee.com/ishadoo/CHShareThird ================================================ Project Name : CHShareThird HTTPS Repo : https://gitee.com/ishadoo/CHShareThird.git SSH Repo : [email protected]:ishadoo/CHShareThird.git Home Page URL : https://gitee.com/ishadoo/CHShareThird ================================================ confirm? (y/n):y copy to .. /CHShareThird/FILE_LICENSE cp: ./templates/FILE_LICENSE: No such file or directory copy to .. /CHShareThird/.gitignore cp: ./templates/gitignore: No such file or directory copy to .. /CHShareThird/CHShareThird.podspec copy to .. /CHShareThird/readme.md cp: ./templates/readme.md: No such file or directory copy to .. /CHShareThird/upload.sh copy to .. /CHShareThird/Podfile editing... sed: .. /CHShareThird/.gitignore: No such file or directory sed: .. /CHShareThird/readme.md: No such file or directory edit finished cleaning... Initialized empty Git repository in /Users/wangchuanhai/code/private/CHShare/CHShareThird/.git/ clean finished finishedCopy the code

Switch to the CHShareThird project and find three more files

  • CHShareThird.podspec
  • Podfile
  • upload.sh
~ / code/private/CHShare CHModuleConfig (master *) » CD.. ------------------------------------------------------------------------------------------------------------------------ --------- ~/code/private/CHShare » ll Total 0 drwxr-xr-x 9 Wangchuanhai staff 288B 3 7 14:25 CHModuleConfig drwxr-xr-x 18 wangchuanhai staff 576B 3 9 17:36 CHShareDesk drwxr-xr-x 18 wangchuanhai staff 576B 3 10 00:39 CHShareHome drwxr-xr-x  16 wangchuanhai staff 512B 3 8 00:25 CHShareMaster drwxr-xr-x 18 wangchuanhai staff 576B 3 9 15:15 CHShareMine drwxr-xr-x 8 wangchuanhai staff 256B 3 10 11:43 CHShareThird ------------------------------------------------------------------------------------------------------------------------ --------- ~/code/private/CHShare » CD CHShareThird ------------------------------------------------------------------------------------------------------------------------ -- -- -- -- -- -- -- -- -- - / code/private/CHShare/CHShareThird (master) » ll total 24 DRWXR xr - x 12 wangchuanhai staff 384 b 3 10 concluded CHShareThird -rw-r--r-- 1 wangchuanhai staff 643B 3 10 11:43 CHShareThird.podspec drwxr-xr-x@ 5 wangchuanhai staff 160B 3 10 11:32 CHShareThird.xcodeproj -rw-r--r-- 1 wangchuanhai staff 213B 3 10 11:43 Podfile -rw-r--r-- 1 wangchuanhai staff 178B 3 10 11:43 upload.sh ------------------------------------------------------------------------------------------------------------------------ ---------Copy the code

Perform the project initialization of CocoaPods

CD to the project root directory and execute pod Install

$ pod install
Copy the code

Create the source SDK

The source code for the modular project is provided in the form of AN SDK for the host project (that is, the module project itself) and the main App, as well as other projects that need to depend on it.

Select the initialized project and open it in Xcode, File -> New -> Target -> Framework

Product Name: ${projectName} + SDK

Creating a Resource Bundle

The Resource Bundle acts as a separate Target to provide support for the SDK for static resources and so on.

File -> New -> Target -> select the Bundle under the macOS module. Since Xcode only supports creating bundles in macOS, select the Bundle option under the macOS module.

Product Name: ${projectName} + Bundle

Create an assets. xcasSets file in the CHShareThirdBundle folder that you just created, and use it as a container for static resources such as images.

In addition, change the Base SDK property of CHShareThirdBundle Targets to iOS support.

Note that the RESOURCE Bundle SDK needs to remove the Executable file option from the info.plist file, otherwise the file will be unavailable.

Creating framework scripts

Copy the compiled framework and bundle files from the simulator’s sandbox directory to the project’s root path for uploading CocoaPods to a private repository.

File -> New -> Target -> Select the Aggregate under Other.

Adding an Execution script

#! /bin/sh
#The name of the target to build
TARGET_NAME=${PROJECT_NAME}
if [[ $1 ]]
then
TARGET_NAME=$1
fi
UNIVERSAL_OUTPUT_FOLDER="${SRCROOT}/${PROJECT_NAME}Upload/"

#Create the output directory and delete the previous framework files
rm -rf "${UNIVERSAL_OUTPUT_FOLDER}"
mkdir -p "${UNIVERSAL_OUTPUT_FOLDER}"

#Build the Framework for the emulator
xcodebuild -target "${TARGET_NAME}SDK" ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphonesimulator BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" clean build

#Copy framework to the univer directory
cp -R "${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/${TARGET_NAME}SDK.framework" "${UNIVERSAL_OUTPUT_FOLDER}"
#Copy the bundle to the univer directory
cp -R "${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/${TARGET_NAME}Bundle.bundle" "${UNIVERSAL_OUTPUT_FOLDER}"

#Open the merged folder
open "${UNIVERSAL_OUTPUT_FOLDER}"

Copy the code

Even after the basic configuration of a module is completed, the dependency of resources needs to be adjusted. From the system level, it is not difficult to understand that the Demo project (the module project itself) depends on the SDK project, and the SDK depends on the Bundle resource.

Next, you can happily code.

Build a Cocoapods version

Podspec file

Change the version number to be consistent with the code tag that is finally committed to Git

– Added vendored_frameworks to refer to framework and bundle resources copied from scripts in the project root directory

Add third-party libraries and system libraries that the project depends on

Pod: : Spec. New do | s | s.n ame = "CHShareThird s.v ersion =" 1.0.20210310 s.s "ummary =" CHShareThird. "spyware doctor escription = <<-DESC this is CHShareThird DESC s.homepage = "https://gitee.com/ishadoo/CHShareThird" s.license = { :type => "MIT", :file => "FILE_LICENSE"} s.athor = {" wang Chuanhai "=> "[email protected]"} s.latform = :ios, "10.0" s.s ource = {: git = > "https://gitee.com/ishadoo/CHShareThird.git", : tag = > s.v ersion} # # # source code form integrated s.s ource_files = "CHShareThird CHShareThird / / *. * * {h, m}" # # support ARC s.r equires_arc = true # # to build the module type s.v endored_frameworks = "CHShareThirdUpload/CHShareThirdSDK framework" s.r esources = "CHShareThirdUpload/CHShareThirdBundle. Bundle" # # rely on third-party libraries as well as the framework of resources s.d. ependency "Masonry" s. ramework = "UIKit" endCopy the code

The upload. Sh file

Add a UIViewController to your project as the root view of the NavigationControler, as shown in the figure below. Now upload the module enclosure to CocoaPods private library.

Once compiled, the framework copies the script and then executes the script to build to the remote CocoaPods library.

Perform before

After performing

Script in the root directory of the project after more than a CHShareThirdUpload folder, which contains CHShareThirdSDK. The framework and CHShareThirdBundle bundle the two files

The code seal plate is used to upload the code to the remote repository, and the seal plate is tagged to match the version in chShareThird. podSpec.

At this point the preparation is complete.

To perform the upload. Sh

~ / code/private/CHShare CHShareThird (master) » ll total 56 DRWXR xr - x 8 wangchuanhai staff 256, 3 b and desired CHShareThird -rw-r--r-- 1 wangchuanhai staff 979B 3 10 17:13 CHShareThird.podspec drwxr-xr-x@ 5 wangchuanhai staff 160B 3 10 16:41 CHShareThird.xcodeproj drwxr-xr-x@ 5 wangchuanhai staff 160B 3 10 15:05 CHShareThird.xcworkspace drwxr-xr-x 4 wangchuanhai staff 128B 3 10 15:29 CHShareThirdBundle drwxr-xr-x 6 wangchuanhai staff 192B 3 10 16:25 CHShareThirdSDK -rw-r--r-- @1 Wangchuanhai staff 1.1k 2 24 15:18 FILE_LICENSE -rw-r--r-- @1 Wangchuanhai staff 232B 3 10 16:33 Podfile -rw-r--r-- 1 wangchuanhai staff 270B 3 10 16:34 Podfile.lock drwxr-xr-x 8 wangchuanhai staff 256B 3 10 16:34 Pods -rw-r--r-- 1 Wangchuanhai staff 956B 3 10 14:53 readme.en.mD-RW-r -- R -- 1 Wangchuanhai staff 1.3k 3 10 14:53 readme.md -rw-r--r-- 1 wangchuanhai staff 178B 3 10 14:50 upload.shCopy the code

In this case, you need to authorize the upload.sh script

~ / code/private/CHShare CHShareThird (master) ». / upload. Sh ZSH: permission denied:. / upload. ShCopy the code

authorization

~ / code/private/CHShare CHShareThird (master) » chmod + x upload. ShCopy the code

Execute the script again

~ / code/private/CHShare CHShareThird (master *) ». / upload. ShCopy the code

After a long compilation, you will receive a successful upload message. Some of the compilation information is as follows:

 ** BUILD SUCCEEDED **
    
   Testing with `xcodebuild`. 
 -> CHShareThird (1.0.2021031001)- NOTE | xcodebuild: note: Using new build system - NOTE | xcodebuild: note: Building targets in parallel - NOTE | xcodebuild: note: Using codesigning identity override: - - NOTE | [iOS] xcodebuild: note: Planning build - NOTE | [iOS] xcodebuild: note: Constructing build description - NOTE | [iOS] xcodebuild: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 6.0, But the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'navigation' from project 'Pods') - NOTE | [iOS] xcodebuild: warning: Skipping code signing because the target does not have an Info.plist file and one is not being generated automatically. (in target 'App' from project 'App') - NOTE | [iOS] xcodebuild: ld: warning: ignoring file CHShareThird/CHShareThirdUpload/CHShareThirdSDK.framework/CHShareThirdSDK, building for iOS Simulator-i386 but attempting to link with file built for iOS Simulator-x86_64 - NOTE | [iOS] xcodebuild: ld: warning: ignoring file CHShareThird/CHShareThirdUpload/CHShareThirdSDK.framework/CHShareThirdSDK, building for iOS Simulator-arm64 but attempting to link with file built for iOS Simulator-x86_64 Updating the `ishadoo-specs' repo
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/ishadoo-specs pull
  Already up to date.

Adding the spec to the `ishadoo-specs' repo

  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/ishadoo-specs status --porcelain
  ?? CHShareThird/
 - [Add] CHShareThird (1.0.2021031001)
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/ishadoo-specs add CHShareThird
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/ishadoo-specs commit --no-verify -m [Add] CHShareThird (1.0.2021031001)[master 95fe617] [Add] CHShareThird (1.0.2021031001) 1 file changed, 29 insertions (+) create mode 100644 CHShareThird / 1.0.2021031001 / CHShareThird podspec Pushing the ` ishadoo - specs' repo
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/ishadoo-specs push origin HEADRemote: Powered by GITEE.COM [GNK 5.0] To https://gitee.com/ishadoo/Specs.git 468 circulating fluidized bed boiler (CFBB).. 95fe617 HEAD -> masterCopy the code

At this point, the first version of the CHShareThird module has been successfully uploaded to the Cocoapods private repository.

Viewing the remote repository

Tracking the remote repository, it’s not hard to see that the new CHShareThird module has successfully uploaded our private repository.

Use the CHShareThird module

Add the following dependency pod ‘CHShareThird’ to the main App’s Podflie file

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

source 'https://gitee.com/ishadoo/Specs.git'
source 'https://github.com/CocoaPods/Specs.git'
source 'https://gitee.com/ishadoo/CHShareMine.git'

target 'CHShareMaster' do
  pod 'CHShareHome'
  pod 'CHShareMine'To:git => 'https://gitee.com/ishadoo/CHShareMine.git'To:branch => 'develop'
  pod 'CHShareDesk'
  pod 'CHShareThird'
end

target 'CHShareSDK' do
  pod 'CHShareHome'
  pod 'CHShareMine'To:git => 'https://gitee.com/ishadoo/CHShareMine.git'To:branch => 'develop'
  pod 'CHShareDesk'
  pod 'CHShareThird'
end
Copy the code

To perform the update pod

~/code/priVate CHShare/CHShareMaster (develop *) » pod update update all the pods Updatinglocal specs repositories
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/ishadoo-specs fetch origin --progress
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/ishadoo-specs rev-parse --abbrev-ref HEAD
  master
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/ishadoo-specs reset --hard origin/master
  HEAD is now at 95fe617 [Add] CHShareThird (1.0.2021031001)
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/master fetch origin --progress
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/master rev-parse --abbrev-ref HEAD
  master
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/master reset --hard origin/master
  HEAD is now at 5b4b6eecd2f8 [Add] TCNetwork 0.2.2
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/gitee-ishadoo-chsharemine fetch origin --progress
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/gitee-ishadoo-chsharemine rev-parse --abbrev-ref HEAD
  master
  $ /usr/bin/git -C /Users/wangchuanhai/.cocoapods/repos/gitee-ishadoo-chsharemine reset --hard origin/master
  HEAD is now at ec3e546 update
Analyzing dependencies
Pre-downloading: `CHShareMine` from `https://gitee.com/ishadoo/CHShareMine.git`, branch `develop`
Downloading dependencies
Installing CHShareMine 1.0.2021030901
Installing CHShareThird (1.0.2021031001)
Generating Pods project
Integrating client project
Pod installation complete! There are 4 dependencies from the Podfile and 5 total pods installed.
Copy the code

At this point, CHShareThird is successfully added to the main App.