> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# iOS 和 macOS 快速入门

> PlayFab Party 的 iOS 和 macOS 集成要求,包括 Xcode 框架链接、麦克风权限和后台音频配置。

本文档列出了将 PlayFab Party 集成到你的 iOS 或 macOS 应用程序中所需的基本先决条件和要求。完成平台特定步骤后,请参阅 [PlayFab Party 快速入门](/services/playfab/multiplayer/networking/quickstart)以完成 PlayFab Party 的入门操作。

## 先决条件

在开始本教程之前,请确保满足以下先决条件:

1. 你已创建 [PlayFab 开发者帐户](https://developer.playfab.com)
2. 你已创建 PlayFab Title,并且该 Title 已被列入 PlayFab Party 的允许列表
3. 你已安装 Xcode 10.2.1 或更高版本
4. 你有权访问 [PlayFab Party 平台仓库](https://github.com/PlayFab/PlayFabParty)
5. 你已创建可用于为部署签名应用的 Apple 开发者帐户。

注意:如果你计划使用 XCode 模拟器进行测试,则需要将应用程序面向 64 位(\$(ARCHS\_STANDARD\_64\_BIT))架构。当前不支持 32 位模拟器。

## 包含所需的库和头文件

### 头文件

* 你需要包含 [PlayFab Party 分发仓库](https://github.com/PlayFab/PlayFabParty/releases)中的以下头文件。

### 框架

* 你需要将应用程序链接到以下框架,这些框架也位于 PlayFab Party 分发包中。
  * iOS:PlayFabParty
  * macOS:PlayFabPartyMac

<Note>
  SSL 库基于 [Open SSL 版本 XXX](https://github.com/openssl/openssl/tree/OpenSSL_1_1_1-stable) 构建。请使用 XXX 或更高版本的 OpenSSL。
</Note>

头文件

[Party 头文件](https://github.com/PlayFab/PlayFabParty/tree/master/include)

除了上述 lib 文件和头文件之外,你还需要 PlayFab SDK 的 lib 和头文件,以及应用所需的任何其他平台特定依赖项。有关更多信息,请查看 iOS 示例的项目文件组织。

## 让 PlayFab Party 在 iOS 或 macOS 上工作的步骤

由于核心 Party 库是使用 C++ 编写的,可以直接从 Objective C++ 代码访问它。为方便起见,我们制作了一个简单的 Objective-C++ 包装类以访问 Party 库功能。总体而言,你需要一个可访问 Party API 方法的类,用于创建网络、连接到网络以及在网络上发送消息。[SimpleClientClass](https://github.com/PlayFab/PlayFabParty/blob/docs/iOS/PartySample/app/inc/SimpleClient.h) 作为示例展示在我们的 iOS 演示应用中。

```obj-c theme={null}
//
//  SimpleClient.h
//  chatdemo_ios

#import <Foundation/Foundation.h>
#import "ChatEventHandler.h"

@interface SimpleClient : NSObject

@property (nonatomic) id<ChatEventHandler> chatEventHandler;

-(void) initialize;
-(void) setHandler:(id<ChatEventHandler>) messageHandler;
-(void) signInLocalUser;

-(void) createNetwork:(NSString*) networkId;
-(void) joinNetwork:(NSString*) networkId;
-(void) leaveNetwork;

-(void) sendTextAsVoice:(NSString*) text;
-(void) sendTextMessage:(NSString*) text;
-(void) setLanguageCode:(int) languageIndex;
-(NSArray *) getLanguageOptions;
-(int) getDefaultLanguageIndex;

-(NSString*) getSelectedUserName;

-(void) tick;

+(void) globalInitialize;
+(void) globalShutdown;

@end

```

上面的对象桥接由一个纯 C++ 实现文件提供支持,该文件调用 [NetworkManager.cpp](https://github.com/PlayFab/PlayFabParty/blob/docs/android/PartySampleNetworkCommon/lib/NetworkManager.cpp),而后者又调用 Party API。

下面是展示各个层级的示例代码段:

SimpleClient Objective-C 接口公开了一种初始化 PlayFab Party 的方法。

```obj-c theme={null}
// In SimpleClient.h
-(void) createNetwork:(NSString*) networkId;
```

SimpleClient 的实现还包括对 C++ 对象的引用,该对象通过 network manager 调用 Party API。

```obj-c theme={null}
// In SimpleClient.mm

@interface SimpleClient ()

@end

@implementation SimpleClient

SimpleClientImpl* m_impl;
```

SimpleClientImpl 是一个 C++ 类,承担创建 Party 网络的繁重工作,如下面的代码段所示:

```cpp theme={null}
void
SimpleClientImpl::CreateNetwork(
    std::string &networkId
    )
{
    if (g_isRunning && g_initializeCompleted)
    {
        Managers::Get<NetworkManager>()->Initialize(c_pfTitleId);
        m_messageHandler->OnStartLoading();
        Managers::Get<NetworkManager>()->CreateAndConnectToNetwork(
            networkId.c_str(),
            [this, networkId](std::string message)
            {
                this->SendSysLogToUI("create network: %s", message.c_str());
                Managers::Get<PlayFabManager>()->SetDescriptor(
                    networkId,
                    message, 
                    [this, message](void)
                    {
                        m_messageHandler->OnEndLoading();
                        this->SendSysLogToUI("set network descriptor %s", "successed");
                        std::string l_message = message;
                        m_messageHandler->OnNetworkCreated(l_message);
                    });
            },
            [this](PartyError error)
            {
                m_messageHandler->OnEndLoading();
                this->SendSysLogToUI("create network failed: %s", GetErrorMessage(error));
            });
    }
}
```

在上面的代码段中,SimpleClient 调用 NetworkManager::CreateAndConnectToNetwork(),后者又调用 [Party.h](https://github.com/PlayFab/PlayFabParty/blob/docs/include/Party.h) 中公开的原始 Party API。

```cpp theme={null}
void 
NetworkManager::CreateAndConnectToNetwork(
    const char *networkId, 
    std::function<void(std::string)> callback, 
    std::function<void(PartyError)> errorCallback
    )
{
    DEBUGLOG("NetworkManager::CreateAndConnectToNetwork()\n");

    // Set the maximum number of devices allowed in a network to 16 devices
    constexpr uint8_t c_maxSampleNetworkDeviceCount = 16;
    static_assert(c_maxSampleNetworkDeviceCount <= c_maxNetworkConfigurationMaxDeviceCount, "Must be less than or equal to c_maxNetworkConfigurationMaxDeviceCount.");

    // Initialize network configuration for Party Network.
    PartyNetworkConfiguration cfg = {};
    cfg.maxDeviceCount = c_maxSampleNetworkDeviceCount;
    cfg.maxDevicesPerUserCount = 1;
    cfg.maxEndpointsPerDeviceCount = 1;
    cfg.maxUserCount = c_maxSampleNetworkDeviceCount;
    cfg.maxUsersPerDeviceCount = 1;

    //Get the uid from the local chat control
    PartyString uid = nullptr;
    PartyError err = m_localUser->GetEntityId(&uid);

    if (PARTY_FAILED(err))
    {
        DEBUGLOG("GetUserIdentifier failed: %s\n", GetErrorMessage(err));
        errorCallback(err);
        return;
    }

    // Setup the network invitation configuration to use the network id as an invitation id and allow anyone to join.
    PartyInvitationConfiguration invitationConfiguration{
        networkId,                                  // invitation identifier
        PartyInvitationRevocability::Anyone,        // revokability
        0,                                          // authorized user count
        nullptr                                     // authorized user list
    };

    // Initialize an empty network descriptor to hold the result of the following call.
    PartyNetworkDescriptor networkDescriptor = {};

    // Create a new network descriptor
    err = PartyManager::GetSingleton().CreateNewNetwork(
        m_localUser,                                // Local User
        &cfg,                                       // Network Config
        0,                                          // Region List Count
        nullptr,                                    // Region List
        &invitationConfiguration,                   // Invitation configuration
        nullptr,                                    // Async Identifier
        &networkDescriptor,                         // OUT network descriptor
        nullptr                                     // applied initialinvitationidentifier.
    );

    if (PARTY_FAILED(err))
    {
        DEBUGLOG("CreateNewNetwork failed: %s\n", GetErrorMessage(err));
        errorCallback(err);
        return;
    }

    // Connect to the new network
    if (InternalConnectToNetwork(networkDescriptor, networkId, errorCallback))
    {
        m_state = NetworkManagerState::WaitingForNetwork;
        m_onnetworkcreated = callback;
        m_onnetworkcreatederror = errorCallback;
        m_onnetworkconnectedError = errorCallback;
    }
}
```

以类似方式,SimpleClient Objective-C 接口中的每个方法都通过 `SimpleClientImpl` 和 `NetworkManager` 映射到 Party API。

## 备注

如果 PlayFab Party 打算用于语音聊天,则应用程序需要被授予麦克风访问权限。为此,请确保将以下属性添加到应用程序的 Info.plist 文件中。

```
<key>NSMicrophoneUsageDescription</key>
<string>The application requires access to the microphone for voice chat.</string>
```

## 后续步骤

完成将 Party 库集成到 iOS 或 macOS 应用程序的平台特定步骤后,请参阅 [PlayFab Party 快速入门](/services/playfab/multiplayer/networking/quickstart)以完成 PlayFab Party 的入门操作。


## Related topics

- [PlayFab Party SDK](/zh-CN/services/playfab/multiplayer/networking/party-sdks/overview.md)
- [macOS 快速入门](/zh-CN/services/playfab/sdks/c/quickstart-macos.md)
- [iOS 快速入门](/zh-CN/services/playfab/sdks/c/quickstart-ios.md)
- [快速入门 (Windows) - Party 和 Multiplayer](/zh-CN/services/playfab/sdks/unified-sdk/quickstart-windows-party.md)
- [使用 Economy v2、Unity IAP 和 Android 快速入门](/zh-CN/services/playfab/economy-monetization/economy-v2/tutorials/getting-started-with-unity-and-android.md)
