如何在不使用Xcode的情况下链接CocoaPods库(integrate_targets为false)

时间:2019-03-06 04:34:22

标签: swift xcode macos cocoa cocoapods

我有一个不带Xcode的快速项目。我想将它与CocoaPods一起使用。给定以下Podfile

platform :osx, '10.11'
install! 'cocoapods', :integrate_targets => false
target 'Foo' do
  pod "PlainPing"
end
pre_install do |installer|
  installer.analysis_result.specifications.each do |s|
    s.swift_version = '4.2' unless s.swift_version
  end
end

我可以轻松地将库构建为.a.swiftmodule文件:

pod install
cd Pods
xcodebuild

但是使用swiftc中的编译库似乎很棘手,我无法猜出正确的搜索路径拼写或用谷歌搜索它们。我最好的选择:

swiftc -I ./build/Release/PlainPing -L ./build/Release/PlainPing -lPlainPing main.swift 

失败

main.swift:2:8: error: cannot load underlying module for 'PlainPing'

似乎-L库搜索路径正在工作,但是swiftc缺少实际使用.a库文件的内容。

1 个答案:

答案 0 :(得分:1)

带有手动CocoaPod编译的版本

要编译同时包含Swift和Objective-C代码的CocoaPods库,请执行以下操作:

  1. 将您的main.swift复制到Pods/PlainPing/Pod/Classes
  2. 编译PlainPing Objective-C代码
  3. 发射PlainPing.swiftmodule
  4. 编译PlainPing发射对象
  5. 编译包含发射对象和main.swift的应用程序

脚本(复制并粘贴到终端中):

 echo "1. Compiling Objective-C code" && \
 clang \
      -c \
      -fmodules \
      -fobjc-weak \
      -arch x86_64 \
      -w \
      SimplePing.m \
 && \
 echo "2. Emitting PlainPing.swiftmodule" && \
 swiftc \
      -emit-module \
      -module-name PlainPing \
      -import-objc-header SimplePing.h \
      PlainPing.swift SimplePingAdapter.swift \
 && \
 echo "3. Compiling PlainPing" && \
 swiftc \
      -emit-object \
      -module-name PlainPing \
      -import-objc-header SimplePing.h \
      PlainPing.swift SimplePingAdapter.swift \
 && \
 echo "4. Compiling app" && \
 swiftc \
      -o app \
      -I . \
      -L . \
      *.o main.swift \
 && \
 echo "5. Running app" && \
 ./app

使用xcodebuild的版本

请确保在use_frameworks!的第二行中添加Podfile

脚本(复制并粘贴到终端中):

echo "Compiling Pods" && \
pod install && \
xcodebuild -project Pods/Pods.xcodeproj \
&& \
echo "Compiling App" && \
dir="build/Pods.build/Release/PlainPing.build/Objects-normal/x86_64" && \
swiftc \
  -o app \
  -L "$dir" \
  -I "$dir" \
  main.swift \
  $(find $dir -name '*.o' -exec echo -n '{} ' \;) \
&& \
echo "Running App" && \
./app

样本main.swift

import Foundation
import PlainPing

PlainPing.ping("www.apple.com", withTimeout: 1.0, completionBlock: { (timeElapsed:Double?, error:Error?) in
    if let latency = timeElapsed {
        print("latency (ms): \(latency)")
    }

    if let error = error {
        print("error: \(error.localizedDescription)")
    }
})

RunLoop.main.run()