switch nsError.code { caseSKError.clientInvalid.rawValue, SKError.paymentNotAllowed.rawValue: showAlert(text: "You are not allowed to make payment.") caseSKError.paymentCancelled.rawValue: showAlert(text: "Payment has been cancelled.") caseSKError.unknown.rawValue, SKError.paymentInvalid.rawValue: fallthrough default: showAlert(text: "Something went wrong making payment.") } }
SwiftUI for now does not work with nested ObservableObject, so if I pass Store to PricingView, changes in PricingPlan does not trigger view update in PricingView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
structMainView: View{ @ObservedObject var store: Store
var body: some View { VStack { geo in } .sheet(isPresented: $showsPricing) { PricingView( isPresented: $showsPricing, store: store ) } } }
There are some workarounds
Pass nested ObservableObject
So that View observes both parent and nested objects.
This forces us to deal with immutability also, as with reference type PricingPlan, someone could just save a reference to it and alter it at some point.
1
structPricingPlan{}
Listen to nested objects changes
Every ObservableObject has a synthesized property objectWillChange that triggers when any @Publisshed property changes
AppKit app has its theme information stored in UserDefaults key AppleInterfaceStyle, if is dark, it contains String Dark.
Another way is to detect appearance via NSView
1 2 3 4 5 6 7 8 9
structR{ staticlet dark = DarkTheme() staticlet light = LightTheme()
staticvar theme: Theme { let isDark = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") == "Dark" return isDark ? dark : light } }
Another way is to rely on appearance on NSView. You can quickly check via NSApp.keyWindow?.effectiveAppearance but notice that keyWindow can be nil when the app is not active since no window is focused for keyboard events. You should use NSApp.windows.first
1
let isDark = NSApp.windows.first?.effectiveAppearance.bestMatch(from: [.darkAqua, .vibrantDark]) == .darkAqua
protocolTheme{ var primaryColor: Color { get } var textColor: Color { get } var text2Color: Color { get } var backgroundColor: Color { get } var background2Color: Color { get } }
extensionTheme{ var primaryColor: Color { Color(hex: 0x1) } }
structDarkTheme: Theme{ ... }
structLightTheme: Theme{ .... }
For SwiftUI, you can colorScheme environment, then use modifier .id(colorScheme) to force SwiftUI to update when color scheme changes
1 2 3 4 5 6 7 8 9
structMainView: View{ @Environment(\.colorScheme) var colorScheme
var body: some View { VStack {} .id(colorScheme) } }
Supposed we want to present a ViewController, and there exist both UIToolbar in both the presenting and presented view controllers.
From iOS 13, the model style is not full screen and interactive. From UITests perspective there are 2 UIToolbar, we need to specify the correct one to avoid multiple match errors
1
let editButton = app.toolbars["EditArticle.Toolbar"].buttons["Edit"]
Use accessibilityElements to specify containment for contentView and buttons. You can use Accessibility Inspector from Xcode to verify.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classArticleCell: UICollectionViewCell{ let authorLabel: UILabel let dateLabel: UILabel
let viewLabel: UILabel let deleteButton: UIButton
privatefuncsetupAccessibility() { contentView.isAccessibilityElement = true contentView.accessibilityLabel = "This article is written by Nobita on Dec 4th 2020"
viewLabel.isAccessibilityElement = true// Default is false viewLabel.accessibilityTraits.insert(.button) // Treat UILabel as button to VoiceOver
This works OK under Voice Over and Accessibility Inspector. However in iOS 14 UITests, only the contentView is recognizable. The workaround is to use XCUICoordinate
1 2 3 4 5 6 7 8 9
let deleteButton = cell.buttons["Delete article"] if deleteButton.waitForExistence(timeout: 1) { deleteButton.tap() } else { let coordinate = cell.coordinate( withNormalizedOffset: CGVector(dx: 0.9, dy: 0.9) ) coordinate.tap() }
funcapplicationDidFinishLaunching(_ aNotification: Notification) { // extend to title bar let contentView = ContentView() // .padding(.top, 24) // can padding to give some space .edgesIgnoringSafeArea(.top)
// window.title = ... // no title // window.toolbar = NSToolbar() // use toolbar if wanted. This triggers .unifiedTitleAndToolbar styleMask window.titlebarAppearsTransparent = true window.titleVisibility = .hidden // hide title window.backgroundColor = R.color.myBackgroundColor // set our preferred background color
I have an issue where if I use HSplitView, some Button are not clickable until I drag the split view handle. The workaround is to use HStack with a Divider
In the app I’m working on Elegant Converter, I usually like preset theme with a custom background color and a matching foreground color.
Thanks to SwiftUI style cascading, I can just declare in root MainView and it will be inherited down the view hierachy.
1 2 3 4 5 6 7 8 9 10
structMainView: View{ var body: some View { HSplitView { ListView() RightView() } .foregroundColor(R.color.text) .background(R.color.background) } }
This works great regardless of system light or dark mode, but in light mode it does not look good, as my designed theme is similar to dark mode. Here the color is pale for default Picker and Button.
The way to fix that is to reset the foregroundColor, take a look at the documentation for foregroundColor
The foreground color to use when displaying this view. Pass nil to remove any custom foreground color and to allow the system or the container to provide its own foreground color. If a container-specific override doesn’t exist, the system uses the primary color.
So we can pass nil and the controls will pick the correct color based on system preferences.
In some cases functions with no arguments might be interchangeable with read-only properties. Although the semantics are similar, there are some stylistic conventions on when to prefer one to another.
Prefer a property over a function when the underlying algorithm:
does not throw
is cheap to calculate (or cached on the first run)
returns the same result over invocations if the object state hasn’t changed
I now use Core Data more often now. Here is how I usually use it, for example in Push Hero
From iOS 10 and macOS 10.12, NSPersistentContainer that simplifies Core Data setup quite a lot. I usually use 1 NSPersistentContainer and its viewContext together with newBackgroundContext attached to that NSPersistentContainer
In Core Data, each context has a queue, except for viewContext using the DispatchQueue.main, and each NSManagedObject retrieved from 1 context is supposed to use within that context queue only, except for objectId property.
Although NSManagedObject subclasses from NSObject, it has a lot of other constraints that we need to be aware of. So it’s safe to treat Core Data as a cache layer, and use our own model on top of it. I usually perform operations on background context to avoid main thread blocking, and automaticallyMergesChangesFromParent handles merge changes automatically for us.
Since we have custom init in ChildView to manually set a State, we need to pass ObservedObject. In the ParentView, use underscore _ to access property wrapper type.
In SwiftUI, specifying maxWidth as .infinity means taking the whole available width of the container. If many children ask for max width, then they will be divided equally. This is similar to weight in LinearLayout in Android or css flex-grow property.
I always find myself asking this question “What define a good developer?” I ‘ve asked many people and the answers vary, they ‘re all correct in certain aspects
Good programmer is someone who has a solid knowledge of the “how-to” both in theory and in practices. Understanding customer requirements clearly and having a vision to fulfill it through dedication and execution !
Good programmer is one who has in depth knowledge of one particular major and wide understanding of many thing else
Algorithm (actually this was my definition)
But I think I find the answer now, it is responsibility
The single most important trait of a professional programmer is personal responsibility. Professional programmers take responsibility for their career, their estimates, their schedule commitments, their mistakes, and their work- manship. A professional programmer does not pass that responsibility off on others.
If you are a professional, then you are responsible for your own career
Professionals take responsibility for the code they write
Professionals are team players
Professionals do not tolerate big bug lists
Professionals do not make a mess
In fact, if we want to be successful, we need to be responsible for our work and our life.
After has recently reminded about his updating APNs provider API which makes me realised a lot has changed about push notifications, both in terms of client and provider approach.
The HTTP/2-based Apple Push Notification service (APNs) provider API lets you take advantage of great features, such as authentication with a JSON Web Token, improved error messaging, and per-notification feedback. If you send push notifications with the legacy binary protocol, we strongly recommend upgrading to the APNs provider API.
From the the iOS client point of view, you pretty much don’t need to care about provider API, as you only need to register for push notification capability and send the device token to your backend, and it’s the backend’s job to send push request to Apple notifications server.
But it’s good to know the underlying mechanism, especially when you want to troubleshoot push notification. Since a push notification failure can be because of many reasons: it could be due to some failed logic in your backend, or that the push certificate has expired, or that you have sent the wrong device token, or that user has turned off push permission in Settings app, or that the push has been delayed.
Here’s also a common abbreviations you need to learn: APNs it is short for Apple Push Notification service. You can think of it as the server your device always has connection with, so you’re ready for any server push messages from it.
What is binary provider API
Push notification feature was first introduced by Apple in 2009 via a fairly complex binary provider API
In short, binary provider API is just a specification about which address and which format to send push request to Apple push server. The binary interface of the production environment is available through gateway.push.apple.com, port 2195 and development environment gateway.sandbox.push.apple.com, port 2195. The binary interface employs a plain TCP socket for binary content that is streaming in nature.
As you can see in the package instruction above, we need specify frame length and data. Data is a key value pairs of multiple informations like device token, expiration, topic, priority.
Send request to the above addresses via secured TLS or SSL channel. The SSL certificate required for these connections is obtained from your developer account.
The new HTTP/2 provider API
The new HTTP2/ provider API is recommended, it has detailed error reporting and better throughput. If you use URLSession which supports the HTTP/1.1 and HTTP/2 protocols. HTTP/2 support, as described by RFC 7540, you will feel familiar.
In short, when you have a notification to send to a user, your provider must construct a POST request and send it to Apple Push Notification service (APNs). Your request must include the following information:
The JSON payload that you want to send
The device token for the user’s device
Request-header fields specifying how to deliver the notification
For token-based authentication, your provider server’s current authentication token
Upon receiving your server’s POST request, APNs validates the request using either the provided authentication token or your server’s certificate. If validation succeeds, APNs uses the provided device token to identify the user’s device. It then tries to send your JSON payload to that device.
So it’s pretty much how you configure URLRequestwith URLSession, specify base url, some request headers including the authorization and the payload body.
Use HTTP/2 and TLS 1.2 or later to establish a connection to the new provider API endpoint. For development serverit is api.sandbox.push.apple.com:443 and for production server it is api.push.apple.com:443. You then send the request as POST and Apple will do its job to verify and send the push notification to the users device.
Certificate vs token based authentication
To send push request to APNs, you need to authenticate to tell that is really from you. APNs support 2 types of authentication, the traditional way with a certificate, and the recently new recommended way with a p8 token.
Certificate based authentication
For certificate based authentication, you will need a p12 certificate which you can obtain and generate from your Developer account.
Because there are sandbox and production push endpoint, few years ago it was required to have separate sandbox and production environment push certificate, which you had to create separately in your Apple developer account, then in testing need to specify the correct push certificate for each environment.
Now around iOS 10 year we can use just 1 single certificate for both sandbox and production, which is a relief for us developers. When we create certificate on Apple developer page, we need to upload a certificate signing request that we can generate from Keychain Access app. After we download the generated push certificate, download and run it in Keychain, there we can generate p12 key file that contains both certificate and private key to sign our push request.
Certificate and provisioning profiles valid for only 1 year. So every year you have to renew push notification certificates, which is also a good and bad thing. Besides that, every app differs from bundle id, so we kinda have to generate certificate for each app.
Token based authentication
Token-based authentication offers a stateless way to communicate with APNs. Stateless communication is faster than certificate-based communication because it doesn’t require APNs to look up the certificate, or other information, related to your provider server. There are other advantages to using token-based authentication:
The cool thing about token is that you can use one token to distribute notifications for all of your company’s apps. You can create in your Apple developer account. Key authentication is the recommended way to authenticate with Apple services, so it is used not only for push services, but also for MusicKit and DeviceCheck.
When you request a key, Apple gives you a 10-character string with the Key ID which you must include this string in your JSON tokens and an authentication token signing key, specified as a text file (with a .p8 file extension). The key is allowed to download once and you need to keep it properly.
The token that you include with your notification requests uses the JSON Web Token (JWT) specification. The token itself contains four key-value pairs
After all, the JSON Web Token is encoded in this authorization HTTP headers in your request like this
For security, APNs requires you to refresh your token regularly. Refresh your token no more than once every 20 minutes and no less than once every 60 minutes.
How to register for push notifications from iOS app
The APIs to register for remote notification has changed over the years.
iOS 7
In iOS 7, we used to use this method registerForRemoteNotificationTypes to register to receive remote notifications of the specified types via Apple Push Notification service.
The types can be UIRemoteNotificationTypeBadge, UIRemoteNotificationTypeAlert, UIRemoteNotificationTypeSound
When you send this message, the device initiates the registration process with Apple Push Notification service. If it succeeds, the app delegate receives a device token in the application:didRegisterForRemoteNotificationsWithDeviceToken: method; if registration doesn’t succeed, the delegate is informed via the application:didFailToRegisterForRemoteNotificationsWithError:method. If the app delegate receives a device token, it should connect with its provider and pass it the token.
iOS 8 with registerUserNotificationSettings
From iOS 8, there’s separation between asking for a remote notification with device token, and with presenting push message to the user. This confused developers as these 2 things are separate now.
First, we use registerForRemoteNotifications to register to receive remote notifications via Apple Push Notification service.
Call this method to initiate the registration process with Apple Push Notification service. If registration succeeds, the app calls your app delegate object’s application(_:didRegisterForRemoteNotificationsWithDeviceToken:) method and passes it a device token. You should pass this token along to the server you use to generate remote notifications for the device. If registration fails, the app calls its app delegate’s application(_:didFailToRegisterForRemoteNotificationsWithError:) method instead.
In short, this is to receive device token from APNs so we can do silent push notification or other things. Note that we need to enable Remote notification capability for Background modes.
To present push message to user via alert, banner, badge or sound, we need to explicitly ask for using this method registerUserNotificationSettings to registers your preferred options for notifying the user.
If your app displays alerts, play sounds, or badges its icon, you must call this method during your launch cycle to request permission to alert the user in these ways. After calling this method, the app calls the application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) method of its app delegate to report the results. You can use that method to determine if your request was granted or denied by the user.
iOS 10 with UserNotifications framework
In iOS 10, Apple introduced UserNotifications and UserNotificationsUI framework and lots of new features to push notifications like actions and attachments.
To ask for permission to present push message from iOS 10, use the new UNUserNotificationCenter which accepts options and block callback with grant status.
There ‘s also UNNotificationAction and UNNotificationAttachment to specify additional actions and attachment to go along with the push message, this is very handy for visual purpose and convenient actions user can perform right away from the push message.
There’s also a convenient UserNotificationsUI that was shipped with iOS 10 that allows us to embed custom view controller from our push message
When an iOS device receives a notification containing an alert, the system displays the contents of the alert in two stages. Initially, it displays an abbreviated banner with the title, subtitle, and two to four lines of body text from the notification. If the user presses the abbreviated banner, iOS displays the full notification interface, including any notification-related actions. The system provides the interface for the abbreviated banner, but you can customize the full interface using a notification content app extension.
Also, there is this callback userNotificationCenter _:willPresent that asks the delegate how to handle a notification that arrived while the app was running in the foreground.
If your app is in the foreground when a notification arrives, the shared user notification center calls this method to deliver the notification directly to your app. If you implement this method, you can take whatever actions are necessary to process the notification or show it when your app is running.
iOS 12 with provisional push
New in iOS 12 is the UNAuthorizationStatus.provisional, which are notifications that appear silently in the user’s notification center without appearing on the user’s home screen. We can start sending them as soon as a user has downloaded and run your app for the first time. You can send provisional push notifications unlimited times unless the user explicitly turns them off.
This is good to send unobtrusive push to users in their Notification Center where they can pick up at a later time.
iOS 13 with apns-push-type
Starting with iOS 13 and watchOS 6, there is apns-push-type which must accurately reflect the contents of your notification’s payload. If there is a mismatch, or if the header is missing on required systems, APNs may return an error.
The apns-push-type header field has six valid values. The descriptions below describe when and how to use these values. For example alert for notifications that trigger a user interaction and background for notifications that deliver content in the background.
Some App Clips may need to schedule or receive notifications to provide value. Consider an App Clip that allows users to order food for delivery: By sending notifications, the App Clip informs the user about an upcoming delivery. If notifications are important for your App Clip’s functionality, enable it to schedule or receive notifications for up to 8 hours after each launch.
Remote notification only with content-available
Besides user interface notification, there is content-available notification that delivers notifications that wake your app and update it in the background. If your app’s server-based content changes infrequently or at irregular intervals, you can use background notifications to notify your app when new content becomes available. Read Pushing Background Updates to Your App
Testing push notification in simulator
We have been able to drag images to the Photos app in simulator for years, but new in Xcode 11.4 is the ability to drag push payload to simulator to simulate remote push notification.
All we have to do is create an apns file with Simulator Target Bundle key to specify our app, then drag to the simulator
Many of the simulator features can be controlled via xcrun simctl command line tool where you can change status bar time, battery info, start and stop certain simulators and send push with xcrun simctl push. This is very handy in case you want to automate things.
Test push notification easily with Push Hero
As iOS developers who need to test push notification a lot, I face this challenge. That’s why I made Push Hero as a native macOS application that allows us to reliably test push notification. It is written in pure Swift with all the new APNs specification in mind.
With Push Hero, we can setup multiple test scenario for different app. Each we can specify the authentication method we want, either with p8 token or p12 certificate based. There’s also input validation and hint helper that explains which field is needed and in which format, so you save time to work on your push testing instead.
New in latest version of Push Hero is the ability to send multiple pushes to multiple device tokens, which is the most frequent request. In the right history pane, there’s information about each request and response content, together with apns id information.
Also in Push Hero is the popup to show explanation for each field, and you need to consult Sending Notification Requests to APNs documentation as there are some specifications there. For example with VoIP push, the apns-topic header field must use your app’s bundle ID with .voip appended to the end. If you’re using certificate-based authentication, you must also register the certificate for VoIP services
Conclusion
Push notification continues to be important for iOS apps, and Apple has over the years improved and changed it for the better. This also means lots of knowledge to keep up with. Understanding provider APNs, setting up certificate and JSON Web Token key can be intimidating and take time.
Hopefully the above summary gets you more understanding into push notification, not only the history of changes in both client and provider API, but also some ways to test it easily.
For List in SwiftUI for macOS, it has default background color because of the enclosing NSScrollView via NSTableView that List uses under the hood. Using listRowBackground also gives no effect
While redesigning UI for my app Push Hero, I ended up with an accordion style to toggle section.
It worked great so far, but after 1 collapsing, all image and text views have reduced opacity. This does not happen for other elements like dropdown button or text.
The culprit is that withAnimation, it seems to apply opacity effect. So the workaround is to disable animation wrappedValue, or to tweak transition so that there’s no opacity adjustment.
1 2 3
if shows.wrappedValue { self.transition(AnyTransition.identity) }
The quick way to add new properties without breaking current saved Codable is to declare them as optional. For example if you use EasyStash library to save and load Codable models.
1 2 3 4 5 6 7
import SwiftUI
structInput: Codable{ var bundleId: String = ""
// New props var notificationId: String?
This new property when using dollar syntax $input.notificationId turn into Binding with optional Binding<Strting?> which is incompatible in SwiftUI when we use Binding.
1 2 3 4
structMaterialTextField: View{ let placeholder: String @Bindingvar text: String }
The solution here is write an extension that converts Binding<String?> to Binding<String>
I’ve used the default SwiftUI to achieve the 2 tab views in SwiftUI. It adds a default box around the content and also opinionated paddings. For now on light mode on macOS, the unselected tab has wrong colors.
The way to solve this is to come up with a custom toggle, that we can style and align the way we want. Here is how I did for my app Push Hero
Using a Text instead of Button here gives me default static text look.
Supposed we want to stitch magazines array into books array. The requirement is to sort them by publishedDate, but must keep preferredOrder of books. One way to solve this is to declare an enum to hold all possible cases, and then do a sort that check every possible combination
However it seems view (UIButton or UILabel) size is the same, just the inner text increases in size. A workaround is to put view inside UIStackView so UIButton or UILabel can automatically changes size.
By default, it runs both after the first render and after every update.
This requirement is common enough that it is built into the useEffect Hook API. You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect:
1 2 3
useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); // Only re-run the effect if count changes
{ "applinks": { "details": [ { "appIDs": ["T78DK947F2.com.onmyway133.myapp"], "components": [ { "#": "no_universal_links", "exclude": true, "comment": "Matches any URL whose fragment equals no_universal_links and instructs the system not to open it as a universal link" } ] } ] }, "webcredentials": { "apps": [ "T78DK947F2.com.onmyway133.myweb" ] } }
Private key
Go to Keys and create new auth key. Configure that key with the primary App ID above