
import SwiftUI
import WhatsNewKit
struct ContentView : View {
var body : some View {
NavigationView {
// ...
}
. whatsNewSheet ( )
}
} Para integrar o uso do Swift Package Manager da Apple, adicione o seguinte como uma dependência ao seu Package.swift :
dependencies: [
. package ( url : " https://github.com/SvenTiigi/WhatsNewKit.git " , from : " 2.0.0 " )
] Ou navegue até o seu projeto Xcode e selecione Swift Packages , clique no ícone "+" e pesquise o WhatsNewKit .
Confira o aplicativo de exemplo para ver o WhatsNewkit em ação. Basta abrir o Example/Example.xcodeproj e executar o esquema "exemplo".

Se você deseja apresentar manualmente um WhatsNewView , pode usar a sheet(whatsNew:) Modificador.
struct ContentView : View {
@ State
var whatsNew : WhatsNew ? = WhatsNew (
title : " WhatsNewKit " ,
features : [
. init (
image : . init (
systemName : " star.fill " ,
foregroundColor : . orange
) ,
title : " Showcase your new App Features " ,
subtitle : " Present your new app features... "
) ,
// ...
]
)
var body : some View {
NavigationView {
// ...
}
. sheet (
whatsNew : self . $whatsNew
)
}
} O modo de apresentação automática permite que você simplesmente declare seus novos recursos por meio do ambiente Swiftui e o WhatsNewkit terá cuidado para apresentar o WhatsNewView correspondente.
Primeiro, adicione um modificador .whatsNewSheet() à visualização em que o WhatsNewView deve ser apresentado.
struct ContentView : View {
var body : some View {
NavigationView {
// ...
}
// Automatically present a WhatsNewView, if needed.
// The WhatsNew that should be presented to the user
// is automatically retrieved from the `WhatsNewEnvironment`
. whatsNewSheet ( )
}
} O modificador .whatsNewSheet() está usando o WhatsNewEnvironment para recuperar um objeto WhatsNew opcional que deve ser apresentado ao usuário para a versão atual. Portanto, você pode configurar facilmente o WhatsNewEnvironment por meio do modificador environment .
extension App : SwiftUI . App {
var body : some Scene {
WindowGroup {
ContentView ( )
. environment (
. whatsNew ,
WhatsNewEnvironment (
// Specify in which way the presented WhatsNew Versions are stored.
// In default the `UserDefaultsWhatsNewVersionStore` is used.
versionStore : UserDefaultsWhatsNewVersionStore ( ) ,
// Pass a `WhatsNewCollectionProvider` or an array of WhatsNew instances
whatsNewCollection : self
)
)
}
}
}
// MARK: - App+WhatsNewCollectionProvider
extension App : WhatsNewCollectionProvider {
/// Declare your WhatsNew instances per version
var whatsNewCollection : WhatsNewCollection {
WhatsNew (
version : " 1.0.0 " ,
// ...
)
WhatsNew (
version : " 1.1.0 " ,
// ...
)
WhatsNew (
version : " 1.2.0 " ,
// ...
)
}
} O WhatsNewEnvironment terá cuidado para determinar o objeto WhatsNew correspondente que deve ser apresentado ao usuário para a versão atual.
Como visto no exemplo anterior, você pode inicializar um WhatsNewEnvironment , especificando o WhatsNewVersionStore e fornecendo uma WhatsNewCollection .
// Initialize WhatsNewEnvironment by passing an array of WhatsNew Instances.
// UserDefaultsWhatsNewVersionStore is used as default WhatsNewVersionStore
let whatsNewEnvironment = WhatsNewEnvironment (
whatsNewCollection : [
WhatsNew (
version : " 1.0.0 " ,
// ...
)
]
)
// Initialize WhatsNewEnvironment with NSUbiquitousKeyValueWhatsNewVersionStore
// which stores the presented versions in iCloud.
// WhatsNewCollection is provided by a `WhatsNewBuilder` closure
let whatsNewEnvironment = WhatsNewEnvironment (
versionStore : NSUbiquitousKeyValueWhatsNewVersionStore ( ) ,
whatsNewCollection : {
WhatsNew (
version : " 1.0.0 " ,
// ...
)
}
) Além disso, o WhatsNewEnvironment inclui um fallback para versões de patch. Por exemplo, quando um usuário instala a versão 1.0.1 e você apenas declarou um WhatsNew para a versão 1.0.0 , o ambiente será automaticamente de falência para a versão 1.0.0 e apresentará o WhatsNewView ao usuário, se necessário.
Se você deseja personalizar ainda mais o comportamento do WhatsNewEnvironment pode subclasse facilmente e substituir a função whatsNew() .
class MyCustomWhatsNewEnvironment : WhatsNewEnvironment {
/// Retrieve a WhatsNew that should be presented to the user, if available.
override func whatsNew ( ) -> WhatsNew ? {
// The current version
let currentVersion = self . currentVersion
// Your declared WhatsNew objects
let whatsNewCollection = self . whatsNewCollection
// The WhatsNewVersionStore used to determine the already presented versions
let versionStore = self . whatsNewVersionStore
// TODO: Determine WhatsNew that should be presented to the user...
}
} Um WhatsNewVersionStore é um tipo de protocolo, responsável por salvar e recuperar versões que foram apresentadas ao usuário.
let whatsNewVersionStore : WhatsNewVersionStore
// Save presented versions
whatsNewVersionStore . save ( presentedVersion : " 1.0.0 " )
// Retrieve presented versions
let presentedVersions = whatsNewVersionStore . presentedVersions
// Retrieve bool value if a given version has already been presented
let hasPresented = whatsNewVersionStore . hasPresented ( " 1.0.0 " )WhatsNewkit vem junto com três implementações predefinidas:
// Persists presented versions in the UserDefaults
let userDefaultsWhatsNewVersionStore = UserDefaultsWhatsNewVersionStore ( )
// Persists presented versions in iCloud using the NSUbiquitousKeyValueStore
let ubiquitousKeyValueWhatsNewVersionStore = NSUbiquitousKeyValueWhatsNewVersionStore ( )
// Stores presented versions in memory. Perfect for testing purposes
let inMemoryWhatsNewVersionStore = InMemoryWhatsNewVersionStore ( ) Se você já possui uma implementação específica para armazenar configurações relacionadas ao usuário, como o Realm ou o Core Data, pode adotar facilmente sua implementação existente no protocolo WhatsNewVersionStore .
Se você estiver usando o NSUbiquitousKeyValueWhatsNewVersionStore , certifique-se de ativar a capacidade de armazenamento de valor-chave do iCloud na seção "Signação e recursos" do seu projeto Xcode.

As seções a seguir explica como uma estrutura WhatsNew pode ser inicializada para descrever os novos recursos para uma determinada versão do seu aplicativo.
let whatsnew = WhatsNew (
// The Version that relates to the features you want to showcase
version : " 1.0.0 " ,
// The title that is shown at the top
title : " What's New " ,
// The features you want to showcase
features : [
WhatsNew . Feature (
image : . init ( systemName : " star.fill " ) ,
title : " Title " ,
subtitle : " Subtitle "
)
] ,
// The primary action that is used to dismiss the WhatsNewView
primaryAction : WhatsNew . PrimaryAction (
title : " Continue " ,
backgroundColor : . accentColor ,
foregroundColor : . white ,
hapticFeedback : . notification ( . success ) ,
onDismiss : {
print ( " WhatsNewView has been dismissed " )
}
) ,
// The optional secondary action that is displayed above the primary action
secondaryAction : WhatsNew . SecondaryAction (
title : " Learn more " ,
foregroundColor : . accentColor ,
hapticFeedback : . selection ,
action : . openURL (
. init ( string : " https://github.com/SvenTiigi/WhatsNewKit " )
)
)
) O WhatsNew.Version Especifica a versão que introduziu certos recursos no seu aplicativo.
// Initialize with major, minor, and patch
let version = WhatsNew . Version (
major : 1 ,
minor : 0 ,
patch : 0
)
// Initialize by string literal
let version : WhatsNew . Version = " 1.0.0 "
// Initialize WhatsNew Version by using the current version of your bundle
let version : WhatsNew . Version = . current ( ) Um WhatsNew.Title representa o texto do título que é renderizado acima dos recursos.
// Initialize by string literal
let title : WhatsNew . Title = " Continue "
// Initialize with text and foreground color
let title = WhatsNew . Title (
text : " Continue " ,
foregroundColor : . primary
)
// On >= iOS 15 initialize with AttributedString using Markdown
let title = WhatsNew . Title (
text : try AttributedString (
markdown : " What's **New** "
)
) Um WhatsNew.Feature Descreva um recurso específico do seu aplicativo e geralmente consiste em uma imagem, título e legenda.
let feature = WhatsNew . Feature (
image : . init (
systemName : " wand.and.stars "
) ,
title : " New Design " ,
subtitle : . init (
try AttributedString (
markdown : " An awesome new _Design_ "
)
)
) O WhatsNew.PrimaryAction permite que você configure o comportamento do botão principal que é usado para descartar o WhatsNewView apresentado
let primaryAction = WhatsNew . PrimaryAction (
title : " Continue " ,
backgroundColor : . blue ,
foregroundColor : . white ,
hapticFeedback : . notification ( . success ) ,
onDismiss : {
print ( " WhatsNewView has been dismissed " )
}
)Nota: Hapticfeedback só será executado no iOS
Um WhatsNew.SecondaryAction que é exibido acima do WhatsNew.PrimaryAction pode ser opcionalmente fornecido ao inicializar uma instância WhatsNew e permite apresentar uma visualização adicional, executar uma ação personalizada ou abrir um URL.
// SecondaryAction that presents a View
let secondaryActionPresentAboutView = WhatsNew . SecondaryAction (
title : " Learn more " ,
foregroundColor : . blue ,
hapticFeedback : . selection ,
action : . present {
AboutView ( )
}
)
// SecondaryAction that opens a URL
let secondaryActionOpenURL = WhatsNew . SecondaryAction (
title : " Read more " ,
foregroundColor : . blue ,
hapticFeedback : . selection ,
action : . open (
url : . init ( string : " https://github.com/SvenTiigi/WhatsNewKit " )
)
)
// SecondaryAction with custom execution
let secondaryActionCustom = WhatsNew . SecondaryAction (
title : " Custom " ,
action : . custom { presentationMode in
// ...
}
)Nota: Hapticfeedback só será executado no iOS
O WhatsNewkit permite que você ajuste o layout de um WhatsNewView apresentado de várias maneiras.
A maneira mais simples é mudar a instância do WhatsNew.Layout.default .
WhatsNew . Layout . default . featureListSpacing = 35Ao usar o estilo de apresentação automática, você pode fornecer um layout padrão ao inicializar o ambiente do WhatsNewenvir.
. environment (
. whatsNew ,
. init (
defaultLayout : WhatsNew . Layout (
showsScrollViewIndicators : true ,
featureListSpacing : 35
) ,
whatsNew : self
)
) Como alternativa, você pode passar um WhatsNew.Layout quando apresentando automaticamente ou manualmente o WhatsNewView
. whatsNewSheet (
layout : WhatsNew . Layout (
contentPadding : . init (
top : 80 ,
leading : 0 ,
bottom : 0 ,
trailing : 0
)
)
) . sheet (
whatsNew : self . $whatsNew ,
layout : WhatsNew . Layout (
footerActionSpacing : 20
)
) Ao usar UIKit ou AppKit você pode usar o WhatsNewViewController .
let whatsNewViewController = WhatsNewViewController (
whatsNew : WhatsNew (
version : " 1.0.0 " ,
// ...
) ,
layout : WhatsNew . Layout (
contentSpacing : 80
)
) Se você deseja apresentar um WhatsNewViewController apenas se a versão da instância do WhatsNew não tiver sido apresentada, você poderá usar o Inicializador de Falhas de Conveniência.
// Verify WhatsNewViewController is available for presentation
guard let whatsNewViewController = WhatsNewViewController (
whatsNew : WhatsNew (
version : " 1.0.0 " ,
// ...
) ,
versionStore : UserDefaultsWhatsNewVersionStore ( )
) else {
// Version of WhatsNew has already been presented
return
}
// Present WhatsNewViewController
// Version will be automatically saved in the provided
// WhatsNewVersionStore when the WhatsNewViewController gets dismissed
self . present ( whatsNewViewController , animated : true )