iOS集成 #

一、环境要求 #

1.1 开发环境 #

工具 版本要求
macOS 12.0+ (Monterey)
Xcode 14.0+
CocoaPods 1.10+
iOS目标版本 13.0+

1.2 安装Xcode #

  1. 从Mac App Store安装Xcode
  2. 安装命令行工具
bash
xcode-select --install

1.3 安装CocoaPods #

bash
sudo gem install cocoapods

# 或使用Homebrew
brew install cocoapods

二、添加iOS平台 #

2.1 添加平台 #

bash
# 添加iOS平台
npx cap add ios

# 同步更新
npx cap sync ios

2.2 打开Xcode项目 #

bash
npx cap open ios

三、Xcode配置 #

3.1 项目结构 #

text
ios/
└── App/
    ├── App.xcworkspace     # 工作空间(使用这个)
    ├── App.xcodeproj       # 项目文件
    ├── App/
    │   ├── AppDelegate.swift
    │   ├── SceneDelegate.swift
    │   ├── Info.plist
    │   ├── Assets.xcassets/
    │   ├── Base.lproj/
    │   └── capacitor.config.json
    ├── Podfile
    └── Pods/

3.2 签名配置 #

  1. 打开Xcode项目
  2. 选择App target
  3. 进入Signing & Capabilities
  4. 选择Team
  5. 配置Bundle Identifier

3.3 Bundle Identifier #

bash
# 在capacitor.config.json中配置
{
    "appId": "com.company.myapp"
}

# 或在Xcode中修改
# Target → General → Bundle Identifier

3.4 版本号配置 #

text
# Xcode中配置
Target → General → Identity

Version (CFBundleShortVersionString): 1.0.0
Build (CFBundleVersion): 1

四、Info.plist配置 #

4.1 基本配置 #

xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <!-- 应用信息 -->
    <key>CFBundleDisplayName</key>
    <string>My App</string>
    
    <key>CFBundleIdentifier</key>
    <string>com.company.myapp</string>
    
    <key>CFBundleVersion</key>
    <string>1</string>
    
    <key>CFBundleShortVersionString</key>
    <string>1.0.0</string>
    
    <!-- 支持的界面方向 -->
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    
    <!-- 状态栏 -->
    <key>UIStatusBarHidden</key>
    <false/>
    
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <true/>
    
    <!-- 启动画面 -->
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
</dict>
</plist>

4.2 权限描述 #

xml
<!-- 相机权限 -->
<key>NSCameraUsageDescription</key>
<string>需要访问相机来拍照</string>

<!-- 相册权限 -->
<key>NSPhotoLibraryUsageDescription</key>
<string>需要访问相册来选择照片</string>

<key>NSPhotoLibraryAddUsageDescription</key>
<string>需要保存照片到相册</string>

<!-- 位置权限 -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>需要获取您的位置信息</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>需要持续获取您的位置信息</string>

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>需要获取您的位置信息</string>

<!-- 麦克风权限 -->
<key>NSMicrophoneUsageDescription</key>
<string>需要访问麦克风来录音</string>

<!-- 蓝牙权限 -->
<key>NSBluetoothAlwaysUsageDescription</key>
<string>需要访问蓝牙</string>

<key>NSBluetoothPeripheralUsageDescription</key>
<string>需要访问蓝牙外设</string>

<!-- 通讯录权限 -->
<key>NSContactsUsageDescription</key>
<string>需要访问通讯录</string>

<!-- 日历权限 -->
<key>NSCalendarsUsageDescription</key>
<string>需要访问日历</string>

<!-- 提醒事项权限 -->
<key>NSRemindersUsageDescription</key>
<string>需要访问提醒事项</string>

<!-- 运动与健身 -->
<key>NSMotionUsageDescription</key>
<string>需要访问运动数据</string>

<!-- 媒体库 -->
<key>NSAppleMusicUsageDescription</key>
<string>需要访问Apple Music</string>

<!-- Face ID -->
<key>NSFaceIDUsageDescription</key>
<string>需要使用Face ID进行身份验证</string>

4.3 后台模式 #

xml
<key>UIBackgroundModes</key>
<array>
    <!-- 后台定位 -->
    <string>location</string>
    
    <!-- 后台音频 -->
    <string>audio</string>
    
    <!-- 后台获取 -->
    <string>fetch</string>
    
    <!-- 远程通知 -->
    <string>remote-notification</string>
    
    <!-- 后台处理 -->
    <string>processing</string>
</array>

4.4 网络安全 #

xml
<!-- 允许任意加载 -->
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

<!-- 或指定例外域名 -->
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

五、CocoaPods配置 #

5.1 Podfile #

ruby
require_relative '../node_modules/@capacitor/ios/scripts/pods_helpers'

platform :ios, '13.0'
use_frameworks!

target 'App' do
  capacitor_pods
  
  # 添加其他依赖
  # pod 'Alamofire'
  # pod 'SDWebImage'
end

post_install do |installer|
  assertDeploymentTarget(installer)
end

5.2 安装Pods #

bash
cd ios/App
pod install
pod update

5.3 常见问题 #

bash
# 清理Pods缓存
pod cache clean --all
pod deintegrate
pod install

六、AppDelegate配置 #

6.1 基本AppDelegate #

swift
import UIKit
import Capacitor

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    func application(_ application: UIApplication, 
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        return true
    }
    
    func application(_ app: UIApplication, 
                     open url: URL, 
                     options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
    }
    
    func application(_ application: UIApplication, 
                     continue userActivity: NSUserActivity, 
                     restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
    }
}

6.2 处理推送通知 #

swift
import UserNotifications

func application(_ application: UIApplication, 
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    // 注册推送通知
    UNUserNotificationCenter.current().requestAuthorization(
        options: [.alert, .sound, .badge]
    ) { granted, error in
        if granted {
            DispatchQueue.main.async {
                application.registerForRemoteNotifications()
            }
        }
    }
    
    return true
}

func application(_ application: UIApplication, 
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // 将token发送到服务器
    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print("Device Token: \(token)")
}

func application(_ application: UIApplication, 
                 didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register: \(error)")
}

6.3 处理深度链接 #

swift
func application(_ app: UIApplication, 
                 open url: URL, 
                 options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    
    // 处理自定义URL Scheme
    if url.scheme == "myapp" {
        // 解析URL并处理
        handleDeepLink(url)
        return true
    }
    
    return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
}

func application(_ application: UIApplication, 
                 continue userActivity: NSUserActivity, 
                 restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
    
    // 处理Universal Links
    if userActivity.activityType == NSUserActivityTypeBrowsingWeb,
       let url = userActivity.webpageURL {
        handleUniversalLink(url)
        return true
    }
    
    return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
}

七、应用图标 #

7.1 配置图标 #

  1. 打开 Assets.xcassets
  2. 选择 AppIcon
  3. 拖入不同尺寸的图标

7.2 图标尺寸 #

设备 尺寸
iPhone 180x180, 120x120
iPad 167x167, 152x152
App Store 1024x1024

7.3 使用cordova-res #

bash
npm install -g cordova-res

# 生成图标
cordova-res ios --skip-config --copy

八、启动画面 #

8.1 配置启动画面 #

  1. 打开 LaunchScreen.storyboard
  2. 自定义启动画面UI

8.2 使用cordova-res #

bash
cordova-res ios --skip-config --copy

九、构建和发布 #

9.1 构建配置 #

text
Target → Build Settings

Swift Language Version: Swift 5
iOS Deployment Target: 13.0

9.2 Archive打包 #

  1. 选择Any iOS Device
  2. Product → Archive
  3. 等待构建完成
  4. Distribute App

9.3 上传到App Store #

  1. 选择上传方式
  2. 选择签名证书
  3. 上传到App Store Connect

9.4 命令行构建 #

bash
# 构建
xcodebuild -workspace App/App.xcworkspace \
    -scheme App \
    -configuration Release \
    -archivePath build/App.xcarchive \
    archive

# 导出IPA
xcodebuild -exportArchive \
    -archivePath build/App.xcarchive \
    -exportOptionsPlist ExportOptions.plist \
    -exportPath build

十、调试技巧 #

10.1 使用Safari调试 #

  1. Safari → 开发 → 模拟器/设备
  2. 选择网页进行调试

10.2 控制台日志 #

swift
print("Debug message")
NSLog("Debug message")

10.3 断点调试 #

在Xcode中设置断点,进行原生代码调试。

十一、总结 #

11.1 关键配置 #

配置项 文件
应用信息 Info.plist
权限描述 Info.plist
依赖管理 Podfile
应用代理 AppDelegate.swift
图标资源 Assets.xcassets

11.2 下一步 #

了解iOS集成后,让我们学习 Android集成

最后更新:2026-03-28