Ending Live Activity in new iOS 16.2 ActivityKit API - ios

I am following along the tutorial at https://www.youtube.com/watch?v=AUOoalBwxos
However, the ActivityKit API used to start and end the live activity have been deprecated in iOS 16.2.
I have figured out how to update the start method to the new API by replacing activity = try? Activity<TimeTrackingAttributes>.request(attributes: attributes, contentState: state, pushType: nil) with:
let activityContent = ActivityContent(state: state, staleDate: Calendar.current.date(byAdding: .hour, value: 3, to: Date())!)
do {
let myActivity = try Activity<TimeTrackingAttributes>.request(attributes: attributes, content: activityContent, pushType: nil)
print("Requested MyActivity live activity. ID: \(myActivity.id)")
} catch let error {
print("Error requesting live activity: \(error.localizedDescription)")
}
However, I am having trouble ending the live activity started with the new API. With the old, deprecated API, I could start and end my live activity. But when I use the old end API, I get the message end(using:dismissalPolicy:)' was deprecated in iOS 16.2: Use end(content:dismissalPolicy:) instead. The old ‘end’ API does not end the activity started with the new 'start' API.
Would anyone be able to offer some advice for how to end a live activity with the new ActivityKit API in iOS 16.2?
Documentation for the new API: https://developer.apple.com/documentation/activitykit/activity/end(_:dismissalpolicy:)
Documentation for the old API: https://developer.apple.com/documentation/activitykit/activity/end(using:dismissalpolicy:)
The full code for ContentView:
import SwiftUI
import ActivityKit
struct ContentView: View {
#State private var isTrackingTime: Bool = false
#State private var startTime: Date? = nil
#State private var activity: Activity<TimeTrackingAttributes>? = nil;
var body: some View {
NavigationView {
VStack {
if let startTime {
Text(startTime, style: .relative)
}
Button {
isTrackingTime.toggle()
if isTrackingTime {
startTime = .now
// start the live activity
let attributes = TimeTrackingAttributes()
guard let startTime else { return }
let state = TimeTrackingAttributes.ContentState(startTime: startTime)
activity = try? Activity<TimeTrackingAttributes>.request(attributes: attributes, contentState: state, pushType: nil)
// TODO: how to match the new 'start' API to the new 'end' API ?
// let activityContent = ActivityContent(state: state, staleDate: Calendar.current.date(byAdding: .hour, value: 3, to: Date())!)
// do {
// let myActivity = try Activity<TimeTrackingAttributes>.request(attributes: attributes, content: activityContent, pushType: nil)
// print("Requested MyActivity live activity. ID: \(myActivity.id)")
// } catch let error {
// print("Error requesting live activity: \(error.localizedDescription)")
// }
} else {
// end the live activity
guard let startTime else { return }
let state = TimeTrackingAttributes.ContentState(startTime: startTime)
// TODO: how to match the new 'end' API to the new 'start' API ?
Task {
await activity?.end(using: state, dismissalPolicy: .immediate)
}
self.startTime = nil
}
} label: {
Text(isTrackingTime ? "STOP" : "START")
.fontWeight(.light)
.foregroundColor(.white)
.frame(width: 200, height: 200)
.background(Circle().fill(isTrackingTime ? .red : .green))
}
.navigationTitle("Basic Time Tracker")
}
}
}
}
The full code for TimeTrackingAttributes:
import Foundation
import ActivityKit
struct TimeTrackingAttributes: ActivityAttributes {
public typealias TimeTrackingStatus = ContentState
public struct ContentState: Codable, Hashable {
var startTime: Date
}
}

Related

Confirm Stripe payment in SwiftUI (iOS 16)

I am using Stripe API to accept card payment in SwiftUI.
I managed to make successful payment using STPPaymentCardTextField wrapped in UIViewRepresentable and confirm it using the provided sheet modifier .paymentConfirmationSheet(....).
The problem appeared when I adopted the new NavigationStack in iOS 16. It appears that the .paymentConfirmationSheet(....) doesn't work properly if it is presented inside the new NavigationStack.
Is there any other way I can confirm card payment in SwiftUI? How can I fix this?
If I switch back to NavigationView it works as expected but I would want to use the new features of NavigationStack.
My demo checkout view and its viewmodel
struct TestCheckout: View {
#ObservedObject var model = TestCheckoutViewModel()
var body: some View {
VStack {
CardField(paymentMethodParams: $model.paymentMethodParams)
Button("Pay") {
model.pay()
}
.buttonStyle(LargeButtonStyle())
.paymentConfirmationSheet(isConfirmingPayment: $model.confirmPayment,
paymentIntentParams: model.paymentIntentParams,
onCompletion: model.onPaymentComplete)
}
}
}
class TestCheckoutViewModel: ObservableObject {
#Published var paymentMethodParams: STPPaymentMethodParams?
#Published var confirmPayment = false
#Published var paymentIntentParams = STPPaymentIntentParams(clientSecret: "")
func pay() {
Task {
do {
// Create dummy payment intent
let paymentIntent = try await StripeManager.shared.getPaymentIntent(orderId: "", amount: 1000)
// Collect card details
let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntent.secret)
paymentIntentParams.paymentMethodParams = paymentMethodParams
// Submit the payment
DispatchQueue.main.async {
self.paymentIntentParams = paymentIntentParams
self.confirmPayment = true
}
} catch {
print(error)
}
}
}
func onPaymentComplete(status: STPPaymentHandlerActionStatus, paymentIntent: STPPaymentIntent?, error: Error?) {
print("Payment completed: \(error)")
}
}
Now this doesn't work
struct TestView: View {
var body: some View {
NavigationStack {
NavigationLink("Checkout", value: "checkout")
.navigationDestination(for: String.self) { string in
if string == "checkout" {
TestCheckout()
}
}
}
}
}
But this does
struct TestView: View {
var body: some View {
TestCheckout()
}
}
The error I get is:
Error Domain=com.stripe.lib Code=50 "There was an unexpected error -- try again in a few seconds" UserInfo={NSLocalizedDescription=There was an unexpected error -- try again in a few seconds, com.stripe.lib:StripeErrorTypeKey=invalid_request_error, com.stripe.lib:StripeErrorCodeKey=payment_intent_unexpected_state, com.stripe.lib:ErrorMessageKey=Nemůžete potvrdit tento Platební záměr, protože v něm chybí platební metoda. Můžete buď aktualizovat Platební záměr s platební metodou a pak jej znovu potvrdit, nebo jej znovu potvrďte přímo s platební metodou.}
Finally I found the problem.
The problem is the #ObservedObject var model = TestCheckoutViewModel().
For some reason it doesn't work with #ObservedObject anymore and it has to be #StateObject.

Why is my #AppStorage not working on SwiftUI?

I'm trying to set up the #AppStorage wrapper in my project.
I'm pulling Texts from a JSON API (see DataModel), and am hoping to store the results in UserDefautls. I want the data to be fetched .OnAppear and stored into the #AppStorage. When the user taps "Get Next Text", I want a new poem to be fetched, and to update #AppStorage with the newest Text data, (which would delete the past Poem stored).
Currently, the code below builds but does not display anything in the Text(currentPoemTitle).
Data Model
import Foundation
struct Poem: Codable, Hashable {
let title, author: String
let lines: [String]
let linecount: String
}
public class FetchPoem: ObservableObject {
// 1.
#Published var poems = [Poem]()
init() {
getPoem()
}
func getPoem() {
let url = URL(string: "https://poetrydb.org/random/1")!
// 2.
URLSession.shared.dataTask(with: url) {(data, response, error) in
do {
if let poemData = data {
// 3.
let decodedData = try JSONDecoder().decode([Poem].self, from: poemData)
DispatchQueue.main.async {
self.poems = decodedData
}
} else {
print("No data")
}
} catch {
print("Error")
}
}.resume()
}
}
TestView
import SwiftUI
struct Test: View {
#ObservedObject var fetch = FetchPoem()
#AppStorage("currentPoemtTitle") var currentPoemTitle = ""
#AppStorage("currentPoemAuthor") var currentPoemAuthor = ""
var body: some View {
VStack{
Text(currentPoemTitle)
Button("Fetch next text") {
fetch.getPoem()
}
}.onAppear{
if let poem = fetch.poems.first {
currentPoemTitle = "\(poem.title)"
currentPoemAuthor = "\(poem.author)"
}
}
}
}
struct Test_Previews: PreviewProvider {
static var previews: some View {
Test()
}
}
What am I missing? Thanks.
Here are a few code edits to get you going.
I added AppStorageKeys to manage the #AppStorage keys, to avoid errors retyping key strings (ie. "currentPoemtTitle")
Your question asked how to update the #AppStorage with the data, and the simple solution is to add the #AppStorage variables within the FetchPoem class and set them within the FetchPoem class after the data is downloaded. This also avoids the need for the .onAppear function.
The purpose of using #ObservedObject is to be able to keep your View in sync with the data. By adding the extra layer of #AppStorage, you make the #ObservedObject sort of pointless. Within the View, I added a Text() to display the title using the #ObservedObject values directly, instead of relying on #AppStorage. I'm not sure if you want this, but it would remove the need for the #AppStorage variables entirely.
I also added a getPoems2() function using Combine, which is a new framework from Apple to download async data. It makes the code a little easier/more efficient... getPoems() and getPoems2() both work and do the same thing :)
Code:
import Foundation
import SwiftUI
import Combine
struct AppStorageKeys {
static let poemTitle = "current_poem_title"
static let poemAuthor = "current_poem_author"
}
struct Poem: Codable, Hashable {
let title, author: String
let lines: [String]
let linecount: String
}
public class FetchPoem: ObservableObject {
#Published var poems = [Poem]()
#AppStorage(AppStorageKeys.poemTitle) var poemTitle = ""
#AppStorage(AppStorageKeys.poemAuthor) var poemAuthor = ""
init() {
getPoem2()
}
func getPoem() {
let url = URL(string: "https://poetrydb.org/random/1")!
URLSession.shared.dataTask(with: url) {(data, response, error) in
do {
guard let poemData = data else {
print("No data")
return
}
let decodedData = try JSONDecoder().decode([Poem].self, from: poemData)
DispatchQueue.main.async {
self.poems = decodedData
self.updateFirstPoem()
}
} catch {
print("Error")
}
}
.resume()
}
func getPoem2() {
let url = URL(string: "https://poetrydb.org/random/1")!
URLSession.shared.dataTaskPublisher(for: url)
// fetch on background thread
.subscribe(on: DispatchQueue.global(qos: .background))
// recieve response on main thread
.receive(on: DispatchQueue.main)
// ensure there is data
.tryMap { (data, response) in
guard
let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw URLError(.badServerResponse)
}
return data
}
// decode JSON data to [Poem]
.decode(type: [Poem].self, decoder: JSONDecoder())
// Handle results
.sink { (result) in
// will return success or failure
print("poetry fetch completion: \(result)")
} receiveValue: { (value) in
// if success, will return [Poem]
// here you can update your view
self.poems = value
self.updateFirstPoem()
}
// After recieving response, the URLSession is no longer needed & we can cancel the publisher
.cancel()
}
func updateFirstPoem() {
if let firstPoem = self.poems.first {
self.poemTitle = firstPoem.title
self.poemAuthor = firstPoem.author
}
}
}
struct Test: View {
#ObservedObject var fetch = FetchPoem()
#AppStorage(AppStorageKeys.poemTitle) var currentPoemTitle = ""
#AppStorage(AppStorageKeys.poemAuthor) var currentPoemAuthor = ""
var body: some View {
VStack(spacing: 10){
Text("App Storage:")
Text(currentPoemTitle)
Text(currentPoemAuthor)
Divider()
Text("Observed Object:")
Text(fetch.poems.first?.title ?? "")
Text(fetch.poems.first?.author ?? "")
Button("Fetch next text") {
fetch.getPoem()
}
}
}
}
struct Test_Previews: PreviewProvider {
static var previews: some View {
Test()
}
}

Build and update lists automatically with SwiftUI and Combine

I'm starting to learn SwiftUI development, I'm making my first basic SwiftUI based news application which I plan on open sourcing but I'm currently stuck. I've been reading Apple's documentation and looking at examples on how to automatically handle data changes in SwiftUI using combine etc. I've found an article, that's suppose to automatically update the list. I haven't been able to see any immediate data changes or anything being logged.
I'm using the same structure as NewsAPI but as an example I've uploaded it to a GitHub repo. I've made a small project and tried updating the data in my repo and trying to see any changes made in my data. I'm honestly trying my best and could really use some pointers or corrections in what my errors may be. I think my confusion lies in #ObservedObject and #Published and how to handle any changes in my content view. The article doesn't show anything they did to handle data changes so maybe I'm missing something?
import Foundation
import Combine
struct News : Codable {
var articles : [Article]
}
struct Article : Codable,Hashable {
let description : String?
let title : String?
let author: String?
let source: Source
let content: String?
let publishedAt: String?
}
struct Source: Codable,Hashable {
let name: String?
}
class NewsData: ObservableObject {
#Published var news: News = News(articles: [])
init() {
guard let url = URL(string: "https://raw.githubusercontent.com/ca13ra1/data/main/data.json") else { return }
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let response = try? JSONDecoder().decode(News.self, from: data) {
DispatchQueue.main.async() {
self.news = response
print("data called")
}
}
}
}
.resume()
}
}
My View
import SwiftUI
import Combine
struct ContentView: View {
#ObservedObject var data: NewsData
var body: some View {
List(data.news.articles , id: \.self) { article in
Text(article.title ?? "")
}
}
}
The data binding in SwiftUI does no extend to synching state with the server. If thats what you want then you need to use some other mechanism to tell the client that there is new data in the server (ie GraphQL, Firebase, send a push, use a web socket, or poll the server).
A simple polling solution would look like this and note you should not be doing network requests in init, only when you get an on appear from the view because SwiftUI eager hydrates its views even when you cannot see them. Similarly you need to cancel polling when you are off screen:
struct Article: Codable, Identifiable {
var id: String
}
final class ViewModel: ObservableObject {
#Published private(set) var articles: [Article] = []
private let refreshSubject = PassthroughSubject<Void, Never>()
private var timerSubscription: AnyCancellable?
init() {
refreshSubject
.map {
URLSession
.shared
.dataTaskPublisher(for: URL(string: "someURL")!)
.map(\.data)
.decode(type: [Article].self, decoder: JSONDecoder())
.replaceError(with: [])
}
.switchToLatest()
.receive(on: DispatchQueue.main)
.assign(to: &$articles)
}
func refresh() {
refreshSubject.send()
guard timerSubscription == nil else { return }
timerSubscription = Timer
.publish(every: 5, on: .main, in: .common)
.autoconnect()
.sink(receiveValue: { [refreshSubject] _ in
refreshSubject.send()
})
}
func onDisappear() {
timerSubscription = nil
}
}
struct MyView: View {
#StateObject private var viewModel = ViewModel()
var body: some View {
List(viewModel.articles) { article in
Text(article.id)
}
.onAppear { viewModel.refresh() }
.onDisappear { viewModel.onDisappear() }
}
}
I've found a nifty swift package which allows me to easily repeat network calls. It's called swift-request. Thanks to #pawello2222 for helping me solve my dilemma.
import Request
class NewsData: ObservableObject {
#Published var news: News = News(articles: [])
init() {
test()
}
func test() {
AnyRequest<News> {
Url("https://raw.githubusercontent.com/ca13ra1/data/main/data.json")
}
.onObject { data in
DispatchQueue.main.async() {
self.news = data
}
}
.update(every: 300)
.update(publisher: Timer.publish(every: 300, on: .main, in: .common).autoconnect())
.call()
}
}
It's now working as expected, probably the easier option.
Demo:

How to ensure WidgetKit view shows correct results from #FetchRequest?

I have an app that uses Core Data with CloudKit. Changes are synced between devices. The main target has Background Modes capability with checked Remote notifications. Main target and widget target both have the same App Group, and both have iCloud capability with Services set to CloudKit and same container in Containers checked.
My goal is to display actual Core Data entries in SwiftUI WidgetKit view.
My widget target file:
import WidgetKit
import SwiftUI
import CoreData
// MARK: For Core Data
public extension URL {
/// Returns a URL for the given app group and database pointing to the sqlite database.
static func storeURL(for appGroup: String, databaseName: String) -> URL {
guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
fatalError("Shared file container could not be created.")
}
return fileContainer.appendingPathComponent("\(databaseName).sqlite")
}
}
var managedObjectContext: NSManagedObjectContext {
return persistentContainer.viewContext
}
var workingContext: NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
context.parent = managedObjectContext
return context
}
var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "Countdowns")
let storeURL = URL.storeURL(for: "group.app-group-countdowns", databaseName: "Countdowns")
let description = NSPersistentStoreDescription(url: storeURL)
container.loadPersistentStores(completionHandler: { storeDescription, error in
if let error = error as NSError? {
print(error)
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
return container
}()
// MARK: For Widget
struct Provider: TimelineProvider {
var moc = managedObjectContext
init(context : NSManagedObjectContext) {
self.moc = context
}
func placeholder(in context: Context) -> SimpleEntry {
return SimpleEntry(date: Date())
}
func getSnapshot(in context: Context, completion: #escaping (SimpleEntry) -> ()) {
let entry = SimpleEntry(date: Date())
return completion(entry)
}
func getTimeline(in context: Context, completion: #escaping (Timeline<Entry>) -> ()) {
var entries: [SimpleEntry] = []
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .minute, value: hourOffset, to: currentDate)!
let entry = SimpleEntry(date: entryDate)
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct SimpleEntry: TimelineEntry {
let date: Date
}
struct CountdownsWidgetEntryView : View {
var entry: Provider.Entry
#FetchRequest(entity: Countdown.entity(), sortDescriptors: []) var countdowns: FetchedResults<Countdown>
var body: some View {
return (
VStack {
ForEach(countdowns, id: \.self) { (memoryItem: Countdown) in
Text(memoryItem.title ?? "Default title")
}.environment(\.managedObjectContext, managedObjectContext)
Text(entry.date, style: .time)
}
)
}
}
#main
struct CountdownsWidget: Widget {
let kind: String = "CountdownsWidget"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider(context: managedObjectContext)) { entry in
CountdownsWidgetEntryView(entry: entry)
.environment(\.managedObjectContext, managedObjectContext)
}
.configurationDisplayName("My Widget")
.description("This is an example widget.")
}
}
struct CountdownsWidget_Previews: PreviewProvider {
static var previews: some View {
CountdownsWidgetEntryView(entry: SimpleEntry(date: Date()))
.previewContext(WidgetPreviewContext(family: .systemSmall))
}
}
But I have a problem: let's say I have 3 Countdown records in the main app:
At the start widget view shows 3 records as expected in preview (UI for adding a widget). But after I add a widget to the home screen, it does not show Countdown rows, only entry.date, style: .time. When timeline entry changes, rows not visible, too. I made a picture to illustrate this better:
Or:
At the start widget view shows 3 records as expected, but after a minute or so, if I delete or add Countdown records in the main app, widget still shows initial 3 values, but I want it to show the actual number of values (to reflect changes). Timeline entry.date, style .time changes, reflected in the widget, but not entries from request.
Is there any way to ensure my widget shows correct fetch request results? Thanks.
Widget views don't observe anything. They're just provided with TimelineEntry data. Which means #FetchRequest, #ObservedObject etc. will not work here.
Enable remote notifications for your container:
let container = NSPersistentContainer(name: "DataModel")
let description = container.persistentStoreDescriptions.first
description?.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
Update your CoreDataManager to observe remote notifications:
class CoreDataManager {
var itemCount: Int?
private var observers = [NSObjectProtocol]()
init() {
fetchData()
observers.append(
NotificationCenter.default.addObserver(forName: .NSPersistentStoreRemoteChange, object: nil, queue: .main) { _ in
// make sure you don't call this too often - notifications may be posted in very short time frames
self.fetchData()
}
)
}
deinit {
observers.forEach(NotificationCenter.default.removeObserver)
}
func fetchData() {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Item")
do {
self.itemCount = try CoreDataStack.shared.managedObjectContext.count(for: fetchRequest)
WidgetCenter.shared.reloadAllTimelines()
} catch {
print("Failed to fetch: \(error)")
}
}
}
Add another field in the Entry:
struct SimpleEntry: TimelineEntry {
let date: Date
let itemCount: Int?
}
Use it all in the Provider:
struct Provider: TimelineProvider {
let coreDataManager = CoreDataManager()
...
func getTimeline(in context: Context, completion: #escaping (Timeline<Entry>) -> Void) {
let entries = [
SimpleEntry(date: Date(), itemCount: coreDataManager.itemCount),
]
let timeline = Timeline(entries: entries, policy: .never)
completion(timeline)
}
}
Now you can display your entry in the view:
struct WidgetExtEntryView: View {
var entry: Provider.Entry
var body: some View {
VStack {
Text(entry.date, style: .time)
Text("Count: \(String(describing: entry.itemCount))")
}
}
}

Pausing a Notification publisher in SwiftUI

When I call a backend service (login, value check…) I use a Notification publisher on the concerned Views to manage the update asynchronously.
I want to unsubscribe to the notifications when the view disappear, or « pause » the publisher.
I went first with the simple « assign » option from the WWDC19 Combine and related SwiftUI talks, then I looked at this great post and the onReceive modifier. However the view keeps updating with the published value even when the view is not visible.
My questions are:
Can I « pause » this publisher when the view is not visible ?
Should I really be concerned by this, does it affect resources (the backend update could trigger a big refresh on list and images display) or should I just let SwiftUI manage under the hood ?
The sample code:
Option 1: onReceive
struct ContentView: View {
#State var info:String = "???"
let provider = DataProvider() // Local for demo purpose, use another pattern
let publisher = NotificationCenter.default.publisher(for: DataProvider.updated)
.map { notification in
return notification.userInfo?["data"] as! String
}
.receive(on: RunLoop.main)
var body: some View {
TabView {
VStack {
Text("Info: \(info)")
Button(action: {
self.provider.startNotifications()
}) {
Text("Start notifications")
}
}
.onReceive(publisher) { (payload) in
self.info = payload
}
.tabItem {
Image(systemName: "1.circle")
Text("Notifications")
}
VStack {
Text("AnotherView")
}
.tabItem {
Image(systemName: "2.circle")
Text("Nothing")
}
}
}
}
Option 2: onAppear / onDisappear
struct ContentView: View {
#State var info:String = "???"
let provider = DataProvider() // Local for demo purpose, use another pattern
#State var cancel: AnyCancellable? = nil
var body: some View {
TabView {
VStack {
Text("Info: \(info)")
Button(action: {
self.provider.startNotifications()
}) {
Text("Start notifications")
}
}
.onAppear(perform: subscribeToNotifications)
.onDisappear(perform: unsubscribeToNotifications)
.tabItem {
Image(systemName: "1.circle")
Text("Notifications")
}
VStack {
Text("AnotherView")
}
.tabItem {
Image(systemName: "2.circle")
Text("Nothing")
}
}
}
private func subscribeToNotifications() {
// publisher to emit events when the default NotificationCenter broadcasts the notification
let publisher = NotificationCenter.default.publisher(for: DataProvider.updated)
.map { notification in
return notification.userInfo?["data"] as! String
}
.receive(on: RunLoop.main)
// keep reference to Cancellable, and assign String value to property
cancel = publisher.assign(to: \.info, on: self)
}
private func unsubscribeToNotifications() {
guard cancel != nil else {
return
}
cancel?.cancel()
}
}
For this test, I use a dummy service:
class DataProvider {
static let updated = Notification.Name("Updated")
var payload = "nothing"
private var running = true
func fetchSomeData() {
payload = Date().description
print("DEBUG new payload : \(payload)")
let dictionary = ["data":payload] // key 'data' provides payload
NotificationCenter.default.post(name: DataProvider.updated, object: self, userInfo: dictionary)
}
func startNotifications() {
running = true
runNotification()
}
private func runNotification() {
if self.running {
self.fetchSomeData()
let soon = DispatchTime.now().advanced(by: DispatchTimeInterval.seconds(3))
DispatchQueue.main.asyncAfter(deadline: soon) {
self.runNotification()
}
} else {
print("DEBUG runNotification will no longer run")
}
}
func stopNotifications() {
running = false
}
}
It seems that there are two publishers name let publisher in your program. Please remove one set of them. Also self.info = payload and publisher.assign(to: \.info, on: self)} are duplicating.
}
.onAppear(perform: subscribeToNotifications)
.onDisappear(perform: unsubscribeToNotifications)
.onReceive(publisher) { (payload) in
// self.info = payload
print(payload)
}
.tabItem {
In the following:
#State var cancel: AnyCancellable? = nil
private func subscribeToNotifications() {
// publisher to emit events when the default NotificationCenter broadcasts the notification
// let publisher = NotificationCenter.default.publisher(for: DataProvider.updated)
// .map { notification in
// return notification.userInfo?["data"] as! String
// }
// .receive(on: RunLoop.main)
// keep reference to Cancellable, and assign String value to property
if cancel == nil{
cancel = publisher.assign(to: \.info, on: self)}
}
private func unsubscribeToNotifications() {
guard cancel != nil else {
return
}
cancel?.cancel()
}
Now you can see, cancel?.cancel() does work and the info label no longer update after you come back from tab2. ~~~Publisher pause Here because subscription has been cancelled.~~~
Publisher is not paused as there is another subscriber in the view , so the print(payload) still works.

Resources