Skip to main content

API Reference

Documentação da API pública do GoAB Survey SDK iOS.


SurveySdkFactory​

Factory para criar instâncias do SDK, acessada via .shared.

create​

func create(
context: SurveyPlatformContext,
accountId: Int32,
apiToken: String,
timeoutMillis: Int64 = 30_000
) -> SurveySdk
ParâmetroTipoDescrição
contextSurveyPlatformContextMarcador de plataforma — no iOS não carrega estado, use SurveyPlatformContext()
accountIdInt32ID da conta GoAB
apiTokenStringToken de API
timeoutMillisInt64Timeout HTTP (milissegundos; padrão: 30 000)

Retorna: instância de SurveySdk (não inicializada até initialize).

Exemplo:

import GoABSurveySDK

let surveySdk: SurveySdk = SurveySdkFactory.shared.create(
context: SurveyPlatformContext(),
accountId: 2,
apiToken: "your-api-token",
timeoutMillis: 30_000
)

SurveyPlatformContext​

Contexto mínimo exigido pela API multiplataforma. No Android envolve o Context; no iOS é um marcador sem propriedades.

SurveyPlatformContext()

SurveyUiHost​

Contexto mínimo que a app host fornece para apresentar surveys. No iOS, envolve diretamente o UIViewController responsável pela apresentação.

class SurveyUiHost {
init(viewController: UIViewController)
}
PropriedadeTipoDescrição
viewControllerUIViewControllerController a partir do qual a survey (WebView) é apresentada

Exemplo:

surveySdk.setPresentationHost(host: SurveyUiHost(viewController: self))

OnSurveyEventListener​

Closure chamado a cada evento da survey — impressão, resposta, minimizar, envio, fecho, etc.

func addOnSurveyEventListener(
listener: @escaping (SurveyAnalyticsEvent) -> Void
) -> OnSurveyEventListener

func removeOnSurveyEventListener(listener: OnSurveyEventListener)

addOnSurveyEventListener retorna um handle opaco (OnSurveyEventListener) que você guarda para remover o listener depois. A tipagem de SurveyAnalyticsEvent, a lista de tipos de evento e exemplos de uso estão em Eventos de Survey.

Exemplo:

let handle = surveySdk.addOnSurveyEventListener { event in
print("event=\(event.eventType) surveyId=\(event.surveyId ?? 0)")
}

// ao encerrar a tela / logout:
surveySdk.removeOnSurveyEventListener(listener: handle)

SurveySdk​

Classe principal do SDK.

initialize​

func initialize() async throws

Prepara o SDK para uso. Chame uma vez antes de sendEvent.

Exemplo:

Task {
try await surveySdk.initialize()
}

isInitialized​

func isInitialized() -> Bool

Retorna: true se initialize concluiu.


sendEvent​

func sendEvent(
eventName: String,
props: [String: Any] = [:]
)

Informa ao SDK que algo aconteceu na app (ex.: o usuário abriu uma tela ou concluiu uma ação). O SDK avalia se deve exibir uma pesquisa.

ParâmetroTipoDescrição
eventNameStringNome do evento (ex.: "screen_view", "purchase")
propsDictionaryPropriedades do evento. Para telas: screen_name, screen_class

Comportamento:

  • Se o SDK ainda não terminou o initialize, o evento fica guardado e é enviado assim que o SDK ficar pronto (até 20 eventos, descartando o mais antigo, e só se tiverem menos de 30 segundos). Trocar o usuário com setUserId ou chamar disposeSurvey descarta os eventos guardados
  • Ignorado se já houver uma pesquisa aberta na tela

Exemplo:

surveySdk.sendEvent(eventName: "screen_view", props: [
"screen_name": "ProductDetail",
"screen_class": "ProductDetailViewController"
])

surveySdk.sendEvent(eventName: "checkout_started", props: [
"cart_value": 150.0
])

setPresentationHost​

func setPresentationHost(host: SurveyUiHost?)

Define de qual UIViewController o SDK pode apresentar pesquisas. Passe nil para remover.


setUserId​

func setUserId(userId: String?)

Define o ID do usuário logado.

  • nil ou string em branco remove o usuário
  • Ao mudar o ID, pesquisas abertas são fechadas
  • Sem um usuário definido, o SDK usa um identificador anônimo próprio (gerado e guardado no aparelho) nas chamadas ao servidor; quando você define o usuário, ele passa a valer no lugar do anônimo

setUserAttributes​

func setUserAttributes(attributes: [String: String]?)

Define atributos do usuário (ex.: plano, segmento, país).

surveySdk.setUserAttributes(attributes: [
"plan": "enterprise",
"locale": "pt-BR"
])

surveySdk.setUserAttributes(attributes: nil) // limpar

disposeSurvey​

func disposeSurvey()

Fecha qualquer pesquisa visível na tela.

Pode ser chamado mesmo antes de initialize.

surveySdk.disposeSurvey()

addOnSurveyEventListener​

func addOnSurveyEventListener(listener: @escaping (SurveyAnalyticsEvent) -> Void) -> OnSurveyEventListener

Regista um observador de eventos da survey. Vários listeners podem coexistir.


removeOnSurveyEventListener​

func removeOnSurveyEventListener(listener: OnSurveyEventListener)

Remove um listener previamente registado com addOnSurveyEventListener.

Exemplo completo​

import GoABSurveySDK
import UIKit

class SurveyManager {
private let surveySdk: SurveySdk

init() {
surveySdk = SurveySdkFactory.shared.create(
context: SurveyPlatformContext(),
accountId: 2,
apiToken: "your-api-token",
timeoutMillis: 30_000
)
}

func start(presentingFrom viewController: UIViewController, userId: String?) {
surveySdk.setPresentationHost(host: SurveyUiHost(viewController: viewController))
surveySdk.setUserId(userId: userId)

Task {
do {
try await surveySdk.initialize()
} catch {
print("Falha na inicialização do Survey SDK: \(error)")
}
}
}

func onCheckoutOpened() {
surveySdk.sendEvent(eventName: "screen_view", props: [
"screen_name": "Checkout"
])
}

func onLogout() {
surveySdk.disposeSurvey()
surveySdk.setUserId(userId: nil)
surveySdk.setUserAttributes(attributes: nil)
}
}

Próximos passos​