

# IVS iOS 回放器 SDK 入门
<a name="ios-getting-started"></a>

本文档将引导您完成 Amazon IVS iOS 回放器 SDK 入门所涉及的步骤。

我们建议您通过 Swift Package Manager 集成播放器 SDK。（或者，您可以手动将框架添加至项目。）

## 建议：集成播放器 SDK（Swift Package Manager）
<a name="ios-integrate-sdk-swift"></a>

1. 从 [https://player.live-video.net/1.51.0/Package.swift](https://player.live-video.net/1.51.0/Package.swift) 下载 Package.swift 文件。

1. 在您的项目中，创建一个名为 AmazonIVSPlayer 的新目录并将其添加到版本控制中。

1. 将下载的 Package.swift 文件放到新目录中。

1. 在您的 Xcode 项目中，转到**文件 > 添加软件包依赖项**，然后选择**添加本地...**

1. 导航到并选择您创建的 AmazonIVSPlayer 目录，然后选择**添加软件包**。

1. 当系统提示**选择 AmazonIVSPlayer 的软件包产品**时，请通过在**添加到目标**部分中设置应用程序目标来将 **AmazonIVSPlayer** 选为**软件包产品**。

1. 选择**添加软件包**。

## 替代方法：手动安装框架
<a name="ios-install-framework-manually"></a>

1. 最新版本下载链接：[https://player.live-video.net/1.51.0/AmazonIVSPlayer.xcframework.zip](https://player.live-video.net/1.51.0/AmazonIVSPlayer.xcframework.zip)。

1. 提取归档的内容。`AmazonIVSPlayer.xcframework` 包含适用于设备和模拟器的开发工具包。

1. 通过以下方法嵌入 `AmazonIVSPlayer.xcframework`：将其拖动到应用程序目标 **General**（常规）选项卡上的 **Frameworks, Libraries, and Embedded Content**（框架、库和嵌入式内容）部分：  
![\[应用程序目标 General（常规）选项卡上的 Frameworks, Libraries, and Embedded Content（框架、库和嵌入式内容）部分：\]](http://docs.aws.amazon.com/zh_cn/ivs/latest/LowLatencyUserGuide/images/iOS_Player_SDK_Guide_xcframework.png)

## 创建播放器
<a name="ios-create-player"></a>

播放器对象是 `IVSPlayer`。按如下方法进行初始化：

------
#### [ Swift ]

```
import AmazonIVSPlayer

let player = IVSPlayer()
```

------
#### [ Objective-C ]

```
#import <AmazonIVSPlayer/AmazonIVSPlayer.h>

IVSPlayer *player = [[IVSPlayer alloc] init];
```

------

## 设置委托
<a name="ios-setup-delegate"></a>

委托回调提供有关回放状态、事件和错误的信息。所有回调都在主队列上调用。

------
#### [ Swift ]

```
// Self must conform to IVSPlayer.Delegate
player.delegate = self
```

------
#### [ Objective-C ]

```
// Self must conform to IVSPlayer.Delegate
player.delegate = self
```

------

## 显示视频
<a name="ios-display-video"></a>

播放器在自定义层 `IVSPlayerLayer` 中显示视频。软件开发工具包还提供了 `IVSPlayerView`，自定义层支持的 `UIView` 子类。选择更方便您的应用程序界面的一种。

在这两种情况下，使用 `player` 属性，均可显示播放器实例中的视频。

------
#### [ Swift ]

```
// When using IVSPlayerView:
playerView.player = player

// When using IVSPlayerLayer:
playerLayer.player = player
```

------
#### [ Objective-C ]

```
// When using IVSPlayerView:
playerView.player = player;

// When using IVSPlayerLayer:
playerLayer.player = player;
```

------

## 加载流
<a name="ios-load-stream"></a>

播放器以异步方式加载流。其状态指示何时可以播放。

------
#### [ Swift ]

```
player.load(url)
```

------
#### [ Objective-C ]

```
[player load:url];
```

------

## 播放视频流
<a name="ios-play-stream"></a>

播放器准备就绪后，使用 `play` 按钮开始播放。使用 `state` 属性中的委托界面或键值观察来观察状态变化。以下是基于委托方法的示例：

------
#### [ Swift ]

```
func player(_ player: IVSPlayer, didChangeState state: IVSPlayer.State) {
    if state == .ready {
        player.play()
    }
}
```

------
#### [ Objective-C ]

```
- (void)player:(IVSPlayer *)player didChangeState:(IVSPlayerState)state {
    if (state == IVSPlayerStateReady) {
        [player play];
    }
}
```

------

## 暂停后台应用程序
<a name="ios-pause-on-app-backgrounding"></a>

播放器不支持后台播放，但不需要完全退出。暂停即可；请参阅下面的示例。

------
#### [ Swift ]

```
override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self,
        selector: #selector(applicationDidEnterBackground(_:)),
        name: UIApplication.didEnterBackgroundNotification,
        object: nil)
}

@objc func applicationDidEnterBackground(_ notification: NSNotification) {
    playerView?.player?.pause()
}
```

------
#### [ Objective-C ]

```
- (void)viewDidLoad {
    [super viewDidLoad];

    NSNotificationCenter *defaultCenter = NSNotificationCenter.defaultCenter;
    [defaultCenter addObserver:self
                      selector:@selector(applicationDidEnterBackground:)
                          name:UIApplicationDidEnterBackgroundNotification
                        object:nil];
}

- (void)applicationDidEnterBackground:(NSNotification *)notification {
    [playerView.player pause];
}
```

------

## 线程安全
<a name="ios-thread-safety"></a>

播放器 API 不是线程安全的。您应该从应用程序主线程创建和使用播放器实例。

## 开发工具包大小
<a name="ios-sdk-size"></a>

Amazon IVS 播放器开发工具包设计为尽可能轻便。有关开发工具包大小的最新信息，请参阅[发布说明](release-notes.md)。

**重要提示：**在评估大小影响时，Xcode 生成的 IPA 的大小不代表下载到用户设备的应用程序的大小。应用商店执行优化以减小应用程序的大小。

## 组合起来
<a name="ios-putting-together"></a>

以下简单的视图控制器代码段在播放器视图中加载并播放 URL。请注意，`playerView` 属性是从 XIB/Storyboard 初始化而来，并且使用 [Identity Inspector 中的“自定义类”部分](https://developer.apple.com/tutorials/SwiftUI)在 Interface Builder 中将其类设置为 `IVSPlayerView`。

------
#### [ Swift ]

```
import AmazonIVSPlayer

class MyViewController: UIViewController {
...
    // Connected in Interface Builder
    @IBOutlet var playerView: IVSPlayerView!

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self,
            selector: #selector(applicationDidEnterBackground(_:)),
            name: UIApplication.didEnterBackgroundNotification,
            object: nil)
    }

    @objc func applicationDidEnterBackground(_ notification: NSNotification) {
        playerView?.player?.pause()
    }
...
    // Assumes this view controller is already loaded.
    // For example, this could be called by a button tap.
    func playVideo(url videoURL: URL) {
        let player = IVSPlayer()
        player.delegate = self
        playerView.player = player
        player.load(videoURL)
    }
}

extension MyViewController: IVSPlayer.Delegate {
    func player(_ player: IVSPlayer, didChangeState state: IVSPlayer.State) {
        if state == .ready {
            player.play()
        }
    }
}
```

------
#### [ Objective-C ]

```
// MyViewController.h

@class IVSPlayerView;

@interface MyViewController: UIViewController
...
// Connected in Interface Builder
@property (nonatomic) IBOutlet IVSPlayerView *playerView;
...
@end


// MyViewController.m

#import <AmazonIVSPlayer/AmazonIVSPlayer.h>

@implementation MyViewController <IVSPlayerDelegate>
...

- (void)viewDidLoad {
    [super viewDidLoad];

    NSNotificationCenter *defaultCenter = NSNotificationCenter.defaultCenter;
    [defaultCenter addObserver:self
                      selector:@selector(applicationDidEnterBackground:)
                          name:UIApplicationDidEnterBackgroundNotification
                        object:nil];
}

- (void)applicationDidEnterBackground:(NSNotification *)notification {
    [playerView.player pause];
}

// Assumes this view controller is already loaded.
// For example, this could be called by a button tap.
- (void)playVideoWithURL:(NSURL *)videoURL {
    IVSPlayer *player = [[IVSPlayer alloc] init];
    player.delegate = self;
    playerView.player = player;
    [player load:videoURL];
}

- (void)player:(IVSPlayer *)player didChangeState:(IVSPlayerState)state {
    if (state == IVSPlayerStateReady) {
        [player play];
    }
}

...
@end
```

------