How to fix UIToolbar Auto Layout issues
Issue #538
Hierarchy
UIToolbarContentView
Workaround that fixes 1 warning
###
Set frame explicitly
Use a non .zero
frame that is close to the view bounds width
Issue #538
Workaround that fixes 1 warning
###
Use a non .zero
frame that is close to the view bounds width
Issue #537
In xcodebuild
, specify launch arguments.
You can specify this under Launch Arguments in Run action of the app scheme or UITest scheme
Screenshot 2019-12-10 at 23 27 02
1 | (lldb) po ProcessInfo().arguments |
In UITests, pass launch arguments from UITest scheme to UITest application
Issue #536
1 | extension UITextField { |
Issue #535
1 | datePicker.setValue(UIColor.green, forKey: "textColor") |
In iOS 14
1 | if #available(iOS 14.0, *) { |
Updated at 2020-06-24 06:32:07
Issue #530
Although UIImageView
frame is correct, image is still cropped. Watch out for any layer.mask
within view
Issue #529
It is up to you to decide how to use the indexPath parameter to identify a given decoration view. Typically, you use the decorationViewKind parameter to identify the type of the decoration view and the indexPath information to distinguish between different instances of that view.
Issue #518
1 | let userDefaults = UserDefaults(suiteName: suiteName) |
https://developer.apple.com/documentation/foundation/userdefaults/1417339-removepersistentdomain
Calling this method is equivalent to initializing a user defaults object with init(suiteName:) passing domainName, and calling the removeObject(forKey:) method on each of its keys.
Issue #504
https://twitter.com/NeoNacho/status/1181245484867801088?s=20
There’s no way to have platform specific sources or targets today, so you’ll have to take a different approach. I would recommend wrapping all OS specific files in #if os and just having one target. For tests, you could do something similar, one test target, but conditional tests
Every files are in Sources
folder, so we can use platform and version checks. For example Omnia is a Swift Package Manager that supports iOS, tvOS, watchOS, macOS and Catalyst.
For macOS only code, need to check for AppKit and Catalyst
https://github.com/onmyway133/Omnia/blob/master/Sources/macOS/ClickedCollectionView.swift
For SwiftUI feature, need to check for iOS 13 and macOS 10.15
https://github.com/onmyway133/Omnia/blob/master/Sources/SwiftUI/Utils/ImageLoader.swift
Issue #496
Read this Restoring Purchased Products to understand the purposes between the 2.
From iOS 7, every app downloaded from the store has a receipt (for downloading/buying the app) at appStoreReceiptURL
. When users purchases something via In App Purchase, the content at appStoreReceiptURL
is updated with purchases information. Most of the cases, you just need to refresh the receipt (at appStoreReceiptURL
) so that you know which transactions users have made.
Users restore transactions to maintain access to content they’ve already purchased. For example, when they upgrade to a new phone, they don’t lose all of the items they purchased on the old phone. Include some mechanism in your app to let the user restore their purchases, such as a Restore Purchases button. Restoring purchases prompts for the user’s App Store credentials, which interrupts the flow of your app: because of this, don’t automatically restore purchases, especially not every time your app is launched.
In most cases, all your app needs to do is refresh its receipt and deliver the products in its receipt. The refreshed receipt contains a record of the user’s purchases in this app, on this device or any other device. However, some apps need to take an alternate approach for one of the following reasons:
If you use Apple-hosted content, restoring completed transactions gives your app the transaction objects it uses to download the content.
If you need to support versions of iOS earlier than iOS 7, where the app receipt isn’t available, restore completed transactions instead.
Refreshing the receipt asks the App Store for the latest copy of the receipt. Refreshing a receipt does not create any new transactions.
Restoring completed transactions creates a new transaction for every completed transaction the user made, essentially replaying history for your transaction queue observer.
More about receipt, from WWDC 2017, What’s new in StoreKit session https://developer.apple.com/videos/play/wwdc2017/303/
You can also watch WWDC 2017, session Advanced StoreKit for more detail https://developer.apple.com/videos/play/wwdc2017/305/
Original answer https://stackoverflow.com/questions/45615106/when-to-refresh-a-receipt-vs-restore-purchases-in-ios/52162283#52162283
Issue #484
Use SwiftMonkey which adds random UITests gestures
Add to UITests target
Failed to determine hittability of Button: Unable to fetch parameterized attribute XC_kAXXCParameterizedAttributeConvertHostedViewPositionFromContext, remote interface does not have this capability.
This happens when using SwiftMonkey and somewhere in our code uses isHittable
, so best to avoid that by having isolated monkey test only
1 | import XCTest |
Another workaround is possibly use addDefaultXCTestPublicActions
other than addDefaultUIAutomationActions
Assertion Failure: MonkeyXCTest.swift:33: Failed to get matching snapshots: Timed out while evaluating UI query.
This seems related to SwiftMonkey trying to snapshot. Workaround is to remove
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
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
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 #473
Use UIScreen.didConnectNotification
1 | NotificationCenter.default.addObserver(forName: UIScreen.didConnectNotification, |
Handle configurationForConnecting
1 | @UIApplicationMain |
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
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 #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
Issue #461
With UIAlertController we can add buttons and textfields, and just that
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.
alert
The trick is here is to have line breaks in message to leave space for our custom view.
1 | let controller = UIAlertController( |
Issue #459
Here are my notes when working with Push Notification
Register to receive push notification
registerForRemoteNotificationTypes is deprecated in iOS 8+
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
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 #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.
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
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
Issue #452
Use UserNotifications
framework
1 | import FirebaseMessaging |
1 | @UIApplicationMain |
A test message from Firebase looks like
1 | [AnyHashable("google.c.a.e"): 1, AnyHashable("google.c.a.ts"): 1570701857, AnyHashable("aps"): { |
Issue #444
To avoid compiler error Unprintable ASCII character found in source file
, from Swift 5, we can use isASCII
.
Run this from the generator app that generates Swift code.
For more check, see Character https://developer.apple.com/documentation/swift/character/3127011-isletter
Watch out for
The above does not seem to work, use find to find
character (copy Sublime Text to see 0x7f character)