iOS 写一个 framework

2 阅读2分钟

1. 准备源码

建议目录:

CropShape/
├── LICENSE
├── README.md
├── CropShape.podspec
└── Sources/
    └── CropShape.swift

对外要用的类型和函数必须标成 public。例如:

import UIKit

public enum CropShape {
    public static func crop(_ image: UIImage, to path: UIBezierPath) -> UIImage? {
        // ...
        return image
    }
}

最低系统版本自己定,下面示例用 iOS 13。

2. 写 podspec

在仓库根目录新建 CropShape.podspec:

Pod::Spec.new do |s|
  s.name         = 'CropShape'
  s.version      = '1.0.0'
  s.summary      = 'Crop an image to a specified shape.'
  s.description  = 'Swift library that crops a UIImage to a specified shape.'
  s.homepage     = 'https://github.com/finolaire/CropShape'
  s.license      = { :type => 'MIT', :file => 'LICENSE' }
  s.author       = { 'finolaire' => '你的邮箱' }
  s.source       = { :git => 'https://github.com/finolaire/CropShape.git', :tag => s.version.to_s }

  s.ios.deployment_target = '13.0'
  s.swift_version = '5.0'
  s.source_files = 'Sources/**/*.swift'
  s.frameworks = 'UIKit'
end

s.version 必须和后面打的 git tag 完全一致。summary 要比 description 短。

3. 本地校验

安装 CocoaPods 后,在仓库根目录执行:

pod lib lint CropShape.podspec --allow-warnings

通过后再继续。这一步只检查本地文件,不要求 tag 已经存在。

4. 打 tag 并推到 GitHub

git add Sources CropShape.podspec README.md
git commit -m "Add CropShape sources and podspec."
git push origin main

git tag 1.0.0
git push origin 1.0.0

tag 名就是 1.0.0,不要加 v 前缀,除非 podspec 里的 s.source 也写成 v#{s.version}。

再用远端 tag 校验一次:

pod spec lint CropShape.podspec --allow-warnings

5. 发布到 CocoaPods

第一次需要注册(CocoaPods 会发确认邮件):

pod trunk register 你的邮箱 'finolaire' --description='Mac'

你的邮箱会收到一封邮件,然后先确定再执行下面命令:

pod trunk me

确认会话有效后发布:

pod trunk push CropShape.podspec --allow-warnings

成功后,别人的 Podfile 写成:

platform :ios, '13.0'
use_frameworks!

target 'App' do
  pod 'CropShape', '~> 1.0'
end

然后执行 pod install,用生成的 .xcworkspace 打开工程,代码里 import CropShape。

索引同步到 CDN 有时要几分钟到几小时。期间可以先用 git 方式安装,不经过 trunk:

pod 'CropShape', :git => 'https://github.com/finolaire/CropShape.git', :tag => '1.0.0'

6. 以后发新版本

改源码,把 podspec 里的 s.version 改成 1.0.1,提交并推送,再打同名 tag,然后重新 pod trunk push。已发布的版本不能覆盖,只能递增版本号。

Pod Test

platform :ios, '16.6'

#source 'https://mirrors.tuna.tsinghua.edu.cn/git/CocoaPods/Specs.git'

target 'change_your_project_name' do
  use_frameworks!

  pod 'CropShape', '1.0.0'

end

记得屏蔽镜像源,如【source 'mirrors.tuna.tsinghua.edu.cn/git/CocoaPo…