Skip to content

準備工作

先安裝相依套件,然後將兩個 xcframework 複製到xcode中。

安裝相依套件

Swift Package Manager

在 Package.swift 的 dependencies 中加入:

swift
dependencies: [
    .package(url: "https://github.com/swarm-cloud/SwarmCloudKit.git", branch: "main")
]

Carthage

編輯 Cartfile:

binary "https://cdn.swarmcloud.net/apple/SwarmCloudKit.json" ~> 3.6.0
binary "https://cdn.swarmcloud.net/apple/Datachannel.json" ~> 1.0.232

然後,執行如下的命令:

bash
carthage update --use-xcframeworks

這個命令會在 Carthage/Build 資料夾中產生編譯好的XCFramework。
依序開啟xcode的 General -> Frameworks, Libraries, and Embedded Content,將所有 XCFramework 拖進來。

CocoaPods

編輯 Podfile

ruby
target 'TargetName' do
# Uncomment the next line if you're using Swift
# use_frameworks!
    pod 'SwarmCloudKit', '~> 3.0'
end

然後,執行如下的命令:

bash
$ pod install

手動匯入

下載預先編譯好的 XCFramework

複製 framework

先解壓縮,然後將 SwarmCloudKit.xcframework 和 datachannel_wrapper.xcframework 拖入 General -> Frameworks, Libraries, and Embedded Content

整合方法

引入 SwarmCloudKit

在工程的 AppDelegate.m 檔案匯入標頭檔:

swift
import SwarmCloudKit
objective-c
#import <SwarmCloudKit/SwarmCloudKit-Swift.h>

初始化 SWCP2pEngine

在工程 AppDelegate.mapplication:didFinishLaunchingWithOptions: 方法中初始化:

swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let config = P2pConfig(
        trackerZone: .Europe       // Set HongKong or USA if you changed zone
    )
    P2pEngine.setup(token: YOUR_TOKEN, config: config)   // replace with your own token
    return true
}
objective-c
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    P2pConfig* config = [P2pConfig defaultConfiguration];
    config.trackerZone = TrackerZoneEurope;     // Set HongKong or USA if you changed zone
    [P2pEngine setupWithToken:YOUR_TOKEN config:config];  // replace with your own token
    return YES;
}

其中 YOUR_TOKEN 是用於標識使用者的字串,請換成自己的token,點擊這裡查看如何註冊 Appid 並取得 token

轉換位址

在程式碼中實例化AVPlayer之後(也可以是其他任何影片播放器),先將URL傳給 SWCP2pEngine,之後將轉換的本地URL傳給播放器:

swift
let parsedUrl = P2pEngine.shared.parseStreamUrl("https://your_stream.m3u8")
_player = AVPlayer.init(url: URL(string: parsedUrl)!)
objective-c
NSString *parsedUrl = [[P2pEngine sharedInstance] parseStreamUrl:@"https://your_stream.m3u8"];
_player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:parsedUrl]];

就這麼簡單,你的播放器已經具備P2P能力了!

範例

取得完整的範例程式

P2P無效問題排查步驟

請參考常見問題

粤ICP备18075581号