> ## 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.

# Introducción a iOS y macOS

> Requisitos de integración de iOS y macOS para PlayFab Party, incluida la vinculación de marcos de Xcode, los derechos de micrófono y la configuración de audio en segundo plano.

Este documento enumera los requisitos previos y requisitos básicos necesarios para integrar PlayFab Party en sus aplicaciones de iOS o macOS. Después de completar los pasos específicos de la plataforma, consulte el [Inicio rápido para PlayFab Party](/services/playfab/multiplayer/networking/quickstart) para terminar de empezar a trabajar con PlayFab Party.

## Requisitos previos

Antes de comenzar este tutorial, asegúrese de que se cumplen los siguientes requisitos previos:

1. Ha creado una [cuenta de desarrollador de PlayFab](https://developer.playfab.com)
2. Ha creado un título de PlayFab y su título se ha agregado a la lista de permitidos para PlayFab Party
3. Tiene instalado Xcode versión 10.2.1 o superior
4. Tiene acceso al [repositorio de plataformas de PlayFab Party](https://github.com/PlayFab/PlayFabParty)
5. Ha creado una cuenta de desarrollador de Apple que se puede usar para firmar su aplicación para la implementación.

NOTA: Si tiene previsto usar el simulador de XCode para realizar pruebas, deberá dirigir su aplicación a la arquitectura de 64 bits (\$(ARCHS\_STANDARD\_64\_BIT)). Actualmente no se admiten los simuladores de 32 bits.

## Inclusión de las bibliotecas y los archivos de encabezado necesarios

### Encabezados

* Deberá incluir los siguientes archivos de encabezado del [repositorio de distribución de PlayFab Party](https://github.com/PlayFab/PlayFabParty/releases).

### Marcos

* Deberá vincular su aplicación con los siguientes marcos que también se encuentran dentro de los paquetes de distribución de PlayFab Party.
  * iOS: PlayFabParty
  * macOS: PlayFabPartyMac

<Note>
  Las bibliotecas SSL se compilan a partir de [Open SSL versión XXX](https://github.com/openssl/openssl/tree/OpenSSL_1_1_1-stable). Use una versión de OpenSSL que sea XXX o superior
</Note>

Encabezados incluidos

[Encabezados de Party](https://github.com/PlayFab/PlayFabParty/tree/master/include)

Además de los archivos lib y los encabezados anteriores, también necesitará las bibliotecas y los encabezados del SDK de PlayFab y cualquier otra dependencia específica de la plataforma que necesite su aplicación. Eche un vistazo a la organización de archivos del proyecto del ejemplo de iOS para obtener más información.

## Pasos para hacer que PlayFab Party funcione en iOS o macOS

Dado que la biblioteca principal de Party está escrita con C++, es directamente accesible desde código Objective C++. Para mayor comodidad, hemos creado una clase contenedora sencilla de Objective-C++ para acceder a la funcionalidad de la biblioteca de Party. A grandes rasgos, querrá una clase que tenga acceso a los métodos de la API de Party para crear una red, conectarse a una red y enviar mensajes a través de una red. La clase [SimpleClientClass](https://github.com/PlayFab/PlayFabParty/blob/docs/iOS/PartySample/app/inc/SimpleClient.h) se muestra como ejemplo en nuestra aplicación de demostración de 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

```

El puente de objetos anterior está respaldado por un archivo de implementación de C++ puro que llama a [NetworkManager.cpp](https://github.com/PlayFab/PlayFabParty/blob/docs/android/PartySampleNetworkCommon/lib/NetworkManager.cpp), que a su vez llama a las API de Party.

Aquí tiene un fragmento de ejemplo que muestra las distintas capas:

La interfaz Objective-C SimpleClient expone un método para inicializar PlayFab Party.

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

La implementación de SimpleClient también incluye una referencia al objeto de C++ que llama a las API de Party a través del administrador de red.

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

@interface SimpleClient ()

@end

@implementation SimpleClient

SimpleClientImpl* m_impl;
```

SimpleClientImpl es una clase de C++ que realiza el trabajo pesado de crear la red de Party, como se muestra en el fragmento de código siguiente:

```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));
            });
    }
}
```

En el fragmento de código anterior, SimpleClient llama a NetworkManager::CreateAndConnectToNetwork(), que a su vez llama a la API de Party sin procesar expuesta en [Party.h](https://github.com/PlayFab/PlayFabParty/blob/docs/include/Party.h)

```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;
    }
}
```

De forma similar, cada método de la interfaz Objective-C de SimpleClient se asigna a la API de Party a través de `SimpleClientImpl` y `NetworkManager`.

## Comentarios

Si PlayFab Party está destinado a usarse para el chat de voz, la aplicación necesita que se le conceda acceso al micrófono. Para ello, asegúrese de que la siguiente propiedad se agrega al archivo Info.plist de la aplicación.

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

## Pasos siguientes

Después de completar los pasos específicos de la plataforma para integrar la biblioteca de Party en su aplicación de iOS o macOS, consulte el [Inicio rápido para PlayFab Party](/services/playfab/multiplayer/networking/quickstart) para terminar de empezar a trabajar con PlayFab Party.


## Related topics

- [SDK de PlayFab Services](/es/services/playfab/sdks/c/index.md)
- [Ciclo de vida del SDK](/es/services/playfab/sdks/c/lifecycle.md)
- [Inicio rápido de macOS](/es/services/playfab/sdks/c/quickstart-macos.md)
- [Notas de la versión de PlayFab Party](/es/services/playfab/multiplayer/networking/release-notes.md)
- [Notas de la versión del SDK de C++ de PlayFab Multiplayer](/es/services/playfab/multiplayer/lobby/lobby-matchmaking-sdks/lobby-and-matchmaking-release-notes.md)
