How to use array of strings in ForEach in SwiftUI
Issue #483
Every item in list must be uniquely identifiable
1 | List { |
In case of primitive, we can just provide id
to conform to Identifiable
1 | extension String: Identifiable { |
Issue #483
Every item in list must be uniquely identifiable
1 | List { |
In case of primitive, we can just provide id
to conform to Identifiable
1 | extension String: Identifiable { |
Issue #482
lineLimit
does not seem to work, use fixedSize instead
Fixes this view at its ideal size.
A view that fixes this view at its ideal size in the dimensions given in fixedDimensions.
1 | extension Text { |
Issue #480
I use modulemap
in my wrapper around CommonCrypto https://github.com/onmyway133/arcane, https://github.com/onmyway133/Reindeer
For those getting header not found
, please take a look https://github.com/onmyway133/Arcane/issues/4 or run xcode-select --install
CCommonCrypto
containing module.modulemap
module CCommonCrypto {
header "/usr/include/CommonCrypto/CommonCrypto.h"
export *
}
${SRCROOT}/Sources/CCommonCrypto
Here is the podspec https://github.com/onmyway133/Arcane/blob/master/Arcane.podspec
s.source_files = 'Sources/**/*.swift'
s.xcconfig = { 'SWIFT_INCLUDE_PATHS' =>
'$(PODS_ROOT)/CommonCryptoSwift/Sources/CCommonCrypto' }
s.preserve_paths = 'Sources/CCommonCrypto/module.modulemap'
Using module_map
does not work, see https://github.com/CocoaPods/CocoaPods/issues/5271
Using Local Development Pod with path
does not work, see https://github.com/CocoaPods/CocoaPods/issues/809
That’s why you see that my Example Podfile https://github.com/onmyway133/CommonCrypto.swift/blob/master/Example/CommonCryptoSwiftDemo/Podfile points to the git repo
target 'CommonCryptoSwiftDemo' do
pod 'CommonCryptoSwift', :git => 'https://github.com/onmyway133/CommonCrypto.swift'
end
Ji is a wrapper around libxml2, and it uses public header approach
It has a header file https://github.com/honghaoz/Ji/blob/master/Source/Ji.h with Target Membership
set to Public
It has a list of header files for libxml2 https://github.com/honghaoz/Ji/tree/master/Source/Ji-libxml
It has Build Settings -> Header Search Paths
$(SDKROOT)/usr/include/libxml2
It has Build Settings -> Other Linker Flags
-lxml2
1 | s.libraries = "xml2" |
🐝 Interesting related posts
From Xcode 10, we can just
1 | import CommonCrypto |
Issue #479
From ISO8601 spec, the problems are the representation and time zone
1 | ISO 8601 = year-month-day time timezone |
Here are some valid strings
1 | 2016-04-08T10:25:30Z |
Use NSDateFormatter
and normalize the date string.
1 | public var stringToDateFormatter: DateFormatter = { |
So here is the format that I’m using in my ISO8601
1 | let formatter = NSDateFormatter() |
Z: The ISO8601 basic format with hours, minutes and optional seconds fields. The format is equivalent to RFC 822 zone format (when optional seconds field is absent)
Locales represent the formatting choices for a particular user, not the user’s preferred language. These are often the same but can be different. For example, a native English speaker who lives in Germany might select English as the language and Germany as the region
On the other hand, if you’re working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is “en_US_POSIX”, a locale that’s specifically designed to yield US English results regardless of both user and system preferences.
“en_US_POSIX” is also invariant in time (if the US, at some point in the future, changes the way it formats dates, “en_US” will change to reflect the new behaviour, but “en_US_POSIX” will not), and between machines (“en_US_POSIX” works the same on iOS as it does on OS X, and as it it does on other platforms).
From iOS 10, we can use NSISO8601DateFormatter
The NSISO8601DateFormatter class generates and parses string representations of dates following the ISO 8601 standard. Use this class to create ISO 8601 representations of dates and create dates from text strings in ISO 8601 format.
Issue #478
Dependencies used
Examples
Errors occur mostly due to linker error
Test targets need to include pods that Main target uses !
or we’ll get “Framework not found”
1 | def app_pods |
Cocoapods builds a framework that contains all the frameworks the Test targets need, and configure it for us
$(FRAMEWORK_SEARCH_PATHS)
We usually have
1 | github "hyperoslo/Sugar" ~> 1.0 |
1 | github "Quick/Nimble" |
Carthage/Build
Configure correct path
$(FRAMEWORK_SEARCH_PATHS)
From Adding frameworks to unit tests or a framework
In rare cases, you may want to also copy each dependency into the build product (e.g., to embed dependencies within the outer framework, or make sure dependencies are present in a test bundle). To do this, create a new “Copy Files” build phase with the “Frameworks” destination, then add the framework reference there as well.
Question
Reference
Issue #477
1 | 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) (iOS |
1 | #if canImport(UIKit) |
In watchOS app, it still can import UIKit
, so for only iOS usage, we need to use os
check
1 | #if canImport(UIKit) && os(iOS) |
1 | #if targetEnvironment(macCatalyst) |
1 | #if targetEnvironment(simulator) |
Issue #476
React Native comes with a default React library, and most CocoaPods libraries for React Native has React as a dependency pod, which causes the conflict
Issue #475
For a snack bar or image viewing, it’s handy to be able to just flick or toss to dismiss
We can use UIKit Dynamic, which was introduced in iOS 7, to make this happen.
Use UIPanGestureRecognizer
to drag view around, UISnapBehavior
to make view snap back to center if velocity is low, and UIPushBehavior
to throw view in the direction of the gesture.
1 | import UIKit |
Issue #474
Go to Project -> Swift Packages, add package. For example https://github.com/onmyway133/EasyStash
Select your WatchKit Extension
target, under Frameworks, Libraries and Embedded Content
add the library
If we use CocoaPods, then it needs to be in WatchKit Extension
1 | target 'MyApp WatchKit Extension' do |
Issue #473
Use UIScreen.didConnectNotification
1 | NotificationCenter.default.addObserver(forName: UIScreen.didConnectNotification, |
Handle configurationForConnecting
1 |
|
Or we can declare in plist
1 | <dict> |
Issue #472
Use convenient code from Omnia
To make view height dynamic, pin UILabel
to edges and center
1 | import UIKit |
Use Auto Layout and basic UIView animation. Use debouncer to avoid hide
gets called for the new show
. Use debouncer instead of DispatchQueue.main.asyncAfter
because it can cancel the previous DispatchWorkItem
1 | import UIKit |
If we add this error message on UIView in ViewController and we use KeyboardHandler to scroll the entire view, then this snack bar will move up as well
1 | final class ErrorMessageHandler { |
One tricky thing is that if we call hide
and then show
immediately, the completion of hide
will be called after and then remove the view.
When we start animation again, the previous animation is not finished, so we need to check
Read UIView.animate
completion
A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called. If the duration of the animation is 0, this block is performed at the beginning of the next run loop cycle. This parameter may be NULL.
1 | private func toggle(shows: Bool) { |
Issue #471
1 | let navigationController = UINavigationController(rootViewController: viewControllerA) |
In view controller B, need to set hidesBottomBarWhenPushed
in init
1 | final class ViewControllerB: UIViewController { |
Issue #470
Use NSTextAttachment
inside NSAttributedString
1 | extension UILabel { |
Issue #469
If there are lots of logics and states inside a screen, it is best to introduce parent and child container, and switch child depends on state. Each child acts as a State handler.
In less logic case, we can introduce a Scenario class that holds the state. So the ViewController
can be very slim. The thing with State is that all possible scenarios are clear and required to be handled
1 | final class UserDetailScenario { |
Issue #468
From onAppeear
Adds an action to perform when the view appears.
In theory, this should be triggered every time this view appears. But in practice, it is only called when it is pushed on navigation stack, not when we return to it.
So if user goes to a bookmark in a bookmark list, unbookmark an item and go back to the bookmark list, onAppear
is not called again and the list is not updated.
1 | import SwiftUI |
So instead of relying on UI state, we should rely on data state, by listening to onReceive
and update our local @State
1 | struct BookmarksView: View { |
Inside our ObservableObject
, we need to trigger changes notification
1 | final class StoreContainer: ObservableObject { |
Updated at 2020-10-03 10:43:47
Issue #467
Declare top dependencies in ExtensionDelegate
1 | class ExtensionDelegate: NSObject, WKExtensionDelegate { |
Reference that in HostingController
. Note that we need to change from generic MainView
to WKHostingController<AnyView>
as environmentObject
returns View
protocol
1 | class HostingController: WKHostingController<AnyView> { |
In theory, the environment object will be propagated down the view hierarchy, but in practice it throws error. So a workaround now is to just pass that environment object down manually
Fatal error: No ObservableObject of type SomeType found
A View.environmentObject(_:) for StoreContainer.Type may be missing as an ancestor of this view
1 | struct MainView: View { |
Updated at 2020-06-26 03:54:01
Issue #466
iOS
1 | View Controller -> View Model | Logic Handler -> Data Handler -> Repo |
Android
1 | Activity -> Fragment -> View Model | Logic Handler -> Data Handler -> Repo |
Issue #465
Use EasyStash
1 | import EasyStash |
1 | import EasyStash |
If Swift has problem compiling because of generic, use try catch to declare in multiple steps in stead of ??
1 | init() { |
Issue #464
1 | typealias Completion = (Result<User, Error>) -> Void |
Issue #463
1 | func zoom(location1: CLLocation, location2: CLLocation) { |
Issue #462
Using object, we don’t need to care about nil
vs false
like in UserDefaults, our object is the source of truth
1 | class StoringHandler<T: Codable> { |
Then subclass StoringHandler
1 | struct OnboardInfo: Codable { |
Issue #461
With UIAlertController we can add buttons and textfields, and just that
1 | func addAction(UIAlertAction) |
To add custom content to UIAlertController, there are some workarounds
Restyle UITextField
and add custom content
By subclassing we can tweak the whole view hierarchy and listen to events like layout subviews, but this can be very fragile.
This is the correct way but takes too much time to imitate UIAlertController, and have to deal with UIVisualEffectView, resize view for different screen sizes and dark mode
We can detect UILabel
to add our custom view below it, using How to find subview recursively in Swift
But a less work approach is to add it above buttons, this is easily achieved by offsetting bottom.
The trick is here is to have line breaks in message to leave space for our custom view.
1 | let controller = UIAlertController( |
Issue #460
1 | extension UIView { |
Issue #459
Here are my notes when working with Push Notification
Register to receive push notification
registerForRemoteNotificationTypes is deprecated in iOS 8+
1 | UIApplication.sharedApplication().registerForRemoteNotifications() |
Register to alert user through UI
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
1 | let types: UIUserNotificationType = [.Badge, .Sound, .Alert] |
You don’t need to wait for registerUserNotificationSettings to callback before calling registerForRemoteNotifications
From iOS 10, use UNNotifications
framework https://onmyway133.github.io/blog/How-to-register-for-alert-push-notification-in-iOS/
From Registering, Scheduling, and Handling User Notifications
Never cache a device token; always get the token from the system whenever you need it. If your app previously registered for remote notifications, calling the registerForRemoteNotifications method again does not incur any additional overhead, and iOS returns the existing device token to your app delegate immediately. In addition, iOS calls your delegate method any time the device token changes, not just in response to your app registering or re-registering
The user can change the notification settings for your app at any time using the Settings app. Because settings can change, always call the registerUserNotificationSettings: at launch time and use the application:didRegisterUserNotificationSettings: method to get the response. If the user disallows specific notification types, avoid using those types when configuring local and remote notifications for your app.
didReceiveRemoteNotification
About application:didReceiveRemoteNotification:
Implement the application:didReceiveRemoteNotification:fetchCompletionHandler: method instead of this one whenever possible. If your delegate implements both methods, the app object calls the application:didReceiveRemoteNotification:fetchCompletionHandler: method.
If the app is not running when a remote notification arrives, the method launches the app and provides the appropriate information in the launch options dictionary. The app does not call this method to handle that remote notification. Instead, your implementation of the application:willFinishLaunchingWithOptions: or application:didFinishLaunchingWithOptions: method needs to get the remote notification payload data and respond appropriately.
About application:didReceiveRemoteNotification:fetchCompletionHandler:
This is for silent push notification with content-available
Unlike the application:didReceiveRemoteNotification: method, which is called only when your app is running in the foreground, the system calls this method when your app is running in the foreground or background
In addition, if you enabled the remote notifications background mode, the system launches your app (or wakes it from the suspended state) and puts it in the background state when a push notification arrives. However, the system does not automatically launch your app if the user has force-quit it. In that situation, the user must relaunch your app or restart the device before the system attempts to launch your app automatically again.
If the user opens your app from the system-displayed alert, the system may call this method again when your app is about to enter the foreground so that you can update your user interface and display information pertaining to the notification.
Usually, the use of push notification is to display a specific article, a specific DetailViewControllerin your app. So the good practices are
When the app is in foreground: Gently display some kind of alert view and ask the user whether he would like to go to that specific page or not
When user is brought from background to foreground, or from terminated to foreground: Just navigate to that specific page. For example, if you use UINavigationController, you can set that specific page the top most ViewController, if you use UITabBarController, you can set that specific page the selected tab, something like that
1 | - func handlePushNotification(userInfo: NSDictionary) { |
Here we create another method handlePushNotification to handle push notification. When you receive push notification, 3 cases can occur
Loud push
No system alert
application:didReceiveRemoteNotification:fetchCompletionHandler: is called
Silent push
No system alert
application:didReceiveRemoteNotification:fetchCompletionHandler: is called
Loud push
System alert
No method called
Tap notification and application:didReceiveRemoteNotification:fetchCompletionHandler: is called
Tap on App Icon and nothing is called
Silent push
No system alert
application:didReceiveRemoteNotification:fetchCompletionHandler: is called. If app is suspended, its state changed to UIApplicationStateBackground
Tap notification and application:didReceiveRemoteNotification:fetchCompletionHandler: is called
Tap on App Icon and nothing is called
Loud push
System alert
No method called
Tap notification and application:didFinishLaunchingWithOptions: with launchOptions, application:didReceiveRemoteNotification:fetchCompletionHandler: is called
Tap on App Icon and application:didFinishLaunchingWithOptions: is called with launchOptions set to nil
Silent push
No system alert
application:didReceiveRemoteNotification:fetchCompletionHandler: is called. If app was not killed by user, it is woke up and state changed to UIApplicationStateInactive.
Tap notification and application:didFinishLaunchingWithOptions: with launchOptions, application:didReceiveRemoteNotification:fetchCompletionHandler: is called
Tap on App Icon and application:didFinishLaunchingWithOptions: is called with launchOptions set to nil
System alert only show if the payload contains alert
1 | { |
For now I see that silent push must contain sound for application:didReceiveRemoteNotification:fetchCompletionHandler: to be called when app is in background
1 | { |
Read Pushing Background Updates to Your App
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. A background notification is a remote notification that doesn’t display an alert, play a sound, or badge your app’s icon. It wakes your app in the background and gives it time to initiate downloads from your server and update its content.
The system treats background notifications as low-priority: you can use them to refresh your app’s content, but the system doesn’t guarantee their delivery. In addition, the system may throttle the delivery of background notifications if the total number becomes excessive. The number of background notifications allowed by the system depends on current conditions, but don’t try to send more than two or three per hour.
I built a macOS app called PushNotification for you to test push notification. It works with certificate and the new key authentication with APNS. Please give it a try
Tutorials that use PushNotifications
In theory, if user disables push notification then silent notification still goes through
but sound
key should be present
1 | { |
When open the app, didReceiveRemoteNotification
is called immediately with the silent push message
I hope you find this article useful. iOS changes fast so some the things I mention may be outdated by the time you read, if so please let me know. Here are some more interesting links
Original post https://medium.com/fantageek/push-notification-in-ios-46d979e5f7ec
Issue #458
For push notification, we can now use just Production Certificate for 2 environments (production and sandbox) instead of Development and Production certificates.
Now for code signing, with Xcode 11 https://developer.apple.com/documentation/xcode_release_notes/xcode_11_release_notes we can just use Apple Development and Apple Distribution certificate for multiple platforms
Signing and capabilities settings are now combined within a new Signing & Capabilities tab in the Project Editor. The new tab enables using different app capabilities across multiple build configurations. The new capabilities library makes it possible to search for available capabilities
Xcode 11 supports the new Apple Development and Apple Distribution certificate types. These certificates support building, running, and distributing apps on any Apple platform. Preexisting iOS and macOS development and distribution certificates continue to work, however, new certificates you create in Xcode 11 use the new types. Previous versions of Xcode don’t support these certificates
Issue #457
From Creating Independent watchOS Apps
The root target is a stub, and acts as a wrapper for your project, so that you can submit it to the App Store. The other two are identical to the targets found in a traditional watchOS project. They represent your WatchKit app and WatchKit extension, respectively.
Issue #456
From WWDC 2018 What’s New in User Notifications
Instead, the notifications from your app will automatically start getting delivered.
Notifications that are delivered with provisional authorization will have a prompt like this on the notification itself. And this will help the users decide after having received a few notifications whether they want to keep getting these notifications or whether they want to turn them off
It’s an automatic trial of the notifications from your app to help your users make a more informed decision about whether they want these notifications.
1 | notificationCenter.requestAuthorization( |
From http://info.localytics.com/blog/ios-12-brings-new-power-to-push-notifications
Provisional Authorization takes advantage of another new feature in iOS 12: the ability for messages to be “delivered quietly.” When a notification is delivered quietly, it can only be seen in the iOS Notification Center, which the user accesses by swiping down from the top of their phone. They don’t appear as banners or show up on the lock screen. As you might have guessed, quiet notifications also don’t make a sound.
If a user taps the “Keep” button, they can decide whether they want your app’s notifications to start getting delivered prominently (i.e. fully opt-in to push notifications) or continue to receive them quietly (i.e. pushes continue to get sent directly to the Notification Center).
The intent of Provisional Authorization is to give users a trial run with your app’s notifications. Apple created Provisional Authorization because it realized that it’s impossible for users to make an informed choice about whether or not they want to receive push notifications from an app until they’ve seen what kinds of messages the app is going to send them.
Updated at 2020-11-11 02:04:01
Issue #455
There are times we want to log if user can receive push notification. We may be tempted to merely use isRegisteredForRemoteNotifications
but that is not enough. From a user ‘s point of view, they can either receive push notification or not. But behind the scene, many factors are in the game. It can be that user has disabled push notification in app settings or in iOS Settings. It can also be that user enables push notification but disables all sound or banner display mechanism.
isRegisteredForRemoteNotifications
is that your app has connected to APNS and get device token, this can be for silent push notificationcurrentUserNotificationSettings
is for user permissions, without this, there is no alert, banner or sound push notification delivered to the app
Here is the check
1 | static var isPushNotificationEnabled: Bool { |
For iOS 10, with the introduction of UserNotifications
framework, instead of checking for currentUserNotificationSettings
, you should use UserNotifications framework
1 | center.getNotificationSettings(completionHandler: { settings in |
Push notification can be delivered to our apps in many ways, and we can ask for that
1 | UNUserNotificationCenter.current() |
User can go to Settings app and turn off any of those at any time, so it’s best to check for that in the settings object
1 | open class UNNotificationSettings : NSObject, NSCopying, NSSecureCoding { |
Original answer https://stackoverflow.com/a/44407710/1418457
Issue #454
From documentation https://developer.apple.com/documentation/usernotificationsui
Customize how local and remote notifications appear on the user’s device by adding a notification content app extension to the bundle of your iOS app. Your extension manages a custom view controller, which you use to present the content from incoming notifications. When a notification arrives, the system displays your view controller in addition to, or in place of, the default system interface.
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.
Use Notification Content Extension
1 | func didReceive(_ notification: UNNotification) { |