
import SwiftUI
import WhatsNewKit
struct ContentView : View {
var body : some View {
NavigationView {
// ...
}
. whatsNewSheet ( )
}
} Para integrar con el Swift Package Manager de Apple, agregue lo siguiente como dependencia a su Package.swift Swift:
dependencies: [
. package ( url : " https://github.com/SvenTiigi/WhatsNewKit.git " , from : " 2.0.0 " )
] O navegue a su proyecto Xcode y luego seleccione Swift Packages , haga clic en el icono "+" y busque WhatsNewKit .
Consulte la aplicación de ejemplo para ver WhatsNewkit en acción. Simplemente abra el Example/Example.xcodeproj y ejecute el esquema "Ejemplo".

Si desea presentar manualmente una WhatsNewView puede usar la 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
)
}
} El modo de presentación automática le permite simplemente declarar sus nuevas características a través del entorno Swiftui y WhatsNewkit tendrá cuidado de presentar la WhatsNewView correspondiente.
Primero agregue un modificador .whatsNewSheet() a la vista donde se debe presentar WhatsNewView .
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 ( )
}
} El modificador .whatsNewSheet() está haciendo uso del WhatsNewEnvironment para recuperar un objeto Opcional WhatsNew que debe presentarse al usuario para la versión actual. Por lo tanto, puede configurar fácilmente WhatsNewEnvironment a través del 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 " ,
// ...
)
}
} WhatsNewEnvironment tendrá cuidado de determinar el objeto WhatsNew coincidente que debe presentarse al usuario para la versión actual.
Como se ve en el ejemplo anterior, puede inicializar un WhatsNewEnvironment al especificar WhatsNewVersionStore y proporcionando una 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 " ,
// ...
)
}
) Además, el WhatsNewEnvironment incluye un respaldo para versiones de parche. Por ejemplo, cuando un usuario instala la versión 1.0.1 y solo ha declarado un WhatsNew para la versión 1.0.0 , el entorno se volverá automáticamente a la versión 1.0.0 y presentará WhatsNewView al usuario si es necesario.
Si desea personalizar aún más el comportamiento del WhatsNewEnvironment puede subclase fácilmente y anular la función 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...
}
} Un WhatsNewVersionStore es un tipo de protocolo responsable de guardar y recuperar versiones que se han presentado al usuario.
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 viene con tres implementaciones 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 ( ) Si ya tiene una implementación específica para almacenar la configuración relacionada con los usuarios, como Realm o Data Core, puede adoptar fácilmente su implementación existente en el Protocolo WhatsNewVersionStore .
Si está utilizando el NSUbiquitousKeyValueWhatsNewVersionStore , asegúrese de habilitar la capacidad de almacenamiento de valor clave iCloud en la sección "Firmación y capacidades" de su proyecto Xcode.

Las siguientes secciones explican cómo se puede inicializar una estructura WhatsNew para describir las nuevas características para una versión dada de su aplicación.
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 " )
)
)
) WhatsNew.Version especifica la versión que ha introducido ciertas funciones en su aplicación.
// 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 ( ) Un WhatsNew.Title representa el texto del título que se representa por encima de las características.
// 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** "
)
) A WhatsNew.Feature describe una característica específica de su aplicación y generalmente consiste en una imagen, título y subtítulo.
let feature = WhatsNew . Feature (
image : . init (
systemName : " wand.and.stars "
) ,
title : " New Design " ,
subtitle : . init (
try AttributedString (
markdown : " An awesome new _Design_ "
)
)
) WhatsNew.PrimaryAction le permite configurar el comportamiento del botón primario que se utiliza para descartar WhatsNewView presentado
let primaryAction = WhatsNew . PrimaryAction (
title : " Continue " ,
backgroundColor : . blue ,
foregroundColor : . white ,
hapticFeedback : . notification ( . success ) ,
onDismiss : {
print ( " WhatsNewView has been dismissed " )
}
)Nota: HapticFeedback solo se ejecutará en iOS
Una WhatsNew.SecondaryAction que se muestra arriba de WhatsNew.PrimaryAction se puede suministrar opcionalmente al inicializar una instancia WhatsNew y le permite presentar una vista adicional, realizar una acción personalizada o abrir una 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 solo se ejecutará en iOS
WhatsNewkit le permite ajustar el diseño de una vista WhatsNewView presentada de varias maneras.
La forma más simple es mutar WhatsNew.Layout.default instancia.
WhatsNew . Layout . default . featureListSpacing = 35Al usar el estilo de presentación automática, puede proporcionar un diseño predeterminado al inicializar WhatsNewenvironment.
. environment (
. whatsNew ,
. init (
defaultLayout : WhatsNew . Layout (
showsScrollViewIndicators : true ,
featureListSpacing : 35
) ,
whatsNew : self
)
) Alternativamente, puede pasar un WhatsNew.Layout cuando se presenta de forma automática o manual WhatsNewView
. whatsNewSheet (
layout : WhatsNew . Layout (
contentPadding : . init (
top : 80 ,
leading : 0 ,
bottom : 0 ,
trailing : 0
)
)
) . sheet (
whatsNew : self . $whatsNew ,
layout : WhatsNew . Layout (
footerActionSpacing : 20
)
) Cuando use UIKit o AppKit puede usar WhatsNewViewController .
let whatsNewViewController = WhatsNewViewController (
whatsNew : WhatsNew (
version : " 1.0.0 " ,
// ...
) ,
layout : WhatsNew . Layout (
contentSpacing : 80
)
) Si desea presentar un WhatsNewViewController solo si la versión de la instancia de WhatsNew no se ha presentado, puede hacer uso del inicializador de conveniencia falla.
// 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 )