What define a good developer

Issue #683

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.

Ref

How to test push notifications in simulator and production iOS apps

Issue #682

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

binary

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.

cer

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.

key

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

Screenshot 2020-10-11 at 06 28 34

After all, the JSON Web Token is encoded in this authorization HTTP headers in your request like this

1
2
3
authorization = bearer eyAia2lkIjogIjhZTDNHM1JSWDciIH0.eyAiaXNzIjogIkM4Nk5WOUpYM0QiLCAiaWF0I
jogIjE0NTkxNDM1ODA2NTAiIH0.MEYCIQDzqyahmH1rz1s-LFNkylXEa2lZ_aOCX4daxxTZkVEGzwIhALvkClnx5m5eAT6
Lxw7LZtEQcH6JENhJTMArwLf3sXwi

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.

Screenshot 2020-10-11 at 06 39 46

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.

1
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert])

abc

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

ui

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.

Screenshot 2020-10-11 at 06 58 34

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.

In a WWDC 2019 session Advances in App Background Execution, apns-priority must be set to 5 for content available notifications.

iOS 14 with ephemeral authorization status and AppClip

From Enable your App Clip to schedule and receive notifications for a short or extended time period.

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

1
2
3
4
5
6
7
8
{
"Simulator Target Bundle": "com.onmyway133.PushHero",
"aps": {
"alert": "Welcome to Push Hero",
"sound": "chime",
"badge": 2
}
}

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.

Screenshot 2020-10-08 at 06 17 12

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.

How to style multiline Text in SwiftUI for macOS

Issue #681

Only need to specify fixedSize on text to preserve ideal height.

The maximum number of lines is 1 if the value is less than 1. If the value is nil, the text uses as many lines as required. The default is nil.

1
2
3
Text(longText)
.lineLimit(nil) // No need
.fixedSize(horizontal: false, vertical: true)

If the Text is inside a row in a List, fixedSize causes the row to be in middle of the List, workaround is to use ScrollView and vertical StackView.

Sometimes for Text to properly size itself, specify an explicit frame width

How to clear List background color in SwiftUI for macOS

Issue #680

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

The solution is to use a library like SwiftUI-Introspect

1
2
3
4
5
6
7
8
9
10
import Introspect

extension List {
func removeBackground() -> some View {
return introspectTableView { tableView in
tableView.backgroundColor = .clear
tableView.enclosingScrollView!.drawsBackground = false
}
}
}

then

1
2
3
4
5
6
List {
ForEach(items) { item in
// view here
}
}
.removeBackground()

Or we can add extension on NSTableView to alter its content when it moves to superview

1
2
3
4
5
6
7
8
extension NSTableView {
open override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()

backgroundColor = NSColor.clear
enclosingScrollView!.drawsBackground = false
}
}

This works OK for me on macOS 10.15.5, 10.15.7 and macOS 10.11 beta. But it was reported crash during review on macOS 10.15.6

The app launches briefly and then quits without error message.

After inspecting crash log, it is because of viewDidMoveToWindow. So it’s wise not to mess with NSTableView for now

1
2
3
4
5
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 com.onmyway133.PushHero 0x0000000104770b0a @objc NSTableView.viewDidMoveToWindow() (in Push Hero) (<compiler-generated>:296)
1 com.apple.AppKit 0x00007fff2d8638ea -[NSView _setWindow:] + 2416
2 com.apple.AppKit 0x00007fff2d8844ea -[NSControl _setWindow:] + 158
3 com.apple.AppKit 0x00007fff2d946ace -[NSTableView _setWindow:] + 306

How to avoid reduced opacity when hiding view with animation in SwiftUI

Issue #679

While redesigning UI for my app Push Hero, I ended up with an accordion style to toggle section.

Screenshot 2020-10-01 at 06 58 33

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
extension View {
func sectionBackground(_ title: String, _ shows: Binding<Bool>) -> some View {
VStack(alignment: .leading) {
HStack {
Text(title.uppercased())
Spacer()
if shows != nil {
SmallButton(
imageName: "downArrow",
tooltip: shows!.wrappedValue ? "Collapse" : "Expand",
action: {
withAnimation(.easeInOut) {
shows!.wrappedValue.toggle()
}
}
)
.rotationEffect(.radians(shows!.wrappedValue ? .pi : 0))
}
}

if shows.wrappedValue {
self
}
}
}
}

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)
}

How to dynamically add items to VStack from list in SwiftUI

Issue #678

Use enumerated to get index so we can assign to item in list. Here is how I show list of device tokens in my app Push Hero

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private var textViews: some View {
let withIndex = input.deviceTokens.enumerated().map({ $0 })
let binding: (Int, Input.DeviceToken) -> Binding<String> = { index, token in
Binding<String>(
get: { token.token },
set: { self.input.deviceTokens[index].token = $0 }
)
}

return VStack {
ForEach(withIndex, id: \.element.id) { index, token in
return DeviceTokenTextView(text: binding(index, token))
}
}
}

How to unwrap Binding with Optional in SwiftUI

Issue #677

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

struct Input: 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
struct MaterialTextField: View {
let placeholder: String
@Binding var text: String
}

The solution here is write an extension that converts Binding<String?> to Binding<String>

1
2
3
4
5
6
7
8
9
10
11
12
extension Binding where Value == String? {
func toNonOptional() -> Binding<String> {
return Binding<String>(
get: {
return self.wrappedValue ?? ""
},
set: {
self.wrappedValue = $0
}
)
}
}

so we can use them as normal

1
MaterialTextField(text: $input.notificationId.toNonOptional())

How to make custom toggle in SwiftUI

Issue #676

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.

Screenshot 2020-09-29 at 06 52 33
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
struct AuthenticationView: View {
@Binding var input: Input

var body: some View {
toggle
}

var toggle: some View {
VStack(alignment: .leading) {
HStack {
HStack(spacing: 0) {
Text("🔑 Key")
.style(selected: input.authentication == .key)
.onTapGesture {
self.input.authentication = .key
}

Text("📰 Certificate")
.style(selected: input.authentication == .certificate)
.onTapGesture {
self.input.authentication = .certificate
}
}
.padding(3)
.background(Color.white.opacity(0.2))
.cornerRadius(6)

Spacer()
}

choose
Spacer()
}
}

var choose: AnyView {
switch input.authentication {
case .key:
return KeyAuthenticationView().erase()
case .certificate:
return CertificateAuthenticationView().erase()
}
}
}

private extension Text {
func style(selected: Bool) -> some View {
return self
.padding(.vertical, 3)
.padding(.horizontal, 4)
.background(selected ? Color.white.opacity(0.5) : Color.clear)
.cornerRadius(6)
}
}

How to use Binding in function in Swift

Issue #675

Use wrappedValue to get the underlying value that Binding contains

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
extension View {
func addOverlay(shows: Binding<Bool>) -> some View {
HStack {
self
Spacer()
}
.overlay(
HStack {
Spacer()
SmallButton(
imageName: "downArrow",
tooltip: shows.wrappedValue ? "Collapse" : "Expand",
action: {
shows.wrappedValue.toggle()
}
)
.rotationEffect(.radians(shows.wrappedValue ? .pi : 0))
}
)
}
}

How to use HSplitView to define 3 panes view in SwiftUI for macOS

Issue #674

Specify minWidth to ensure miminum width, and use .layoutPriority(1) for the most important pane.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import SwiftUI

struct MainView: View {
@EnvironmentObject var store: Store

var body: some View {
HSplitView {
LeftPane()
.padding()
.frame(minWidth: 200, maxWidth: 500)
MiddlePane(store: store)
.padding()
.frame(minWidth: 500)
.layoutPriority(1)
RightPane()
.padding()
.frame(minWidth: 300)
}
.background(R.color.background)
}
}

How to draw arc corner using Bezier Path

Issue #673

To draw rounded 2 corners at top left and top right, let’s start from bottom left

1
2
3
4
5
6
7
8
9
10
let path = UIBezierPath()
// bottom left
path.move(to: CGPoint(x: 0, y: bounds.height))
// top left corner
path.addArc(withCenter: CGPoint(x: radius, y: radius), radius: radius, startAngle: CGFloat.pi, endAngle: CGFloat.pi * 3 / 2, clockwise: true)
// top right corner
path.addArc(withCenter: CGPoint(x: bounds.width - radius, y: radius), radius: radius, startAngle: CGFloat.pi * 3 / 2, endAngle: 0, clockwise: true)
// bottom right
path.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
path.close()
Screenshot 2020-09-15 at 14 16 01

cc

Read more

How to stitch and sort array in Swift

Issue #672

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
struct Book {
let preferredOrder: Int
let publishedDate: Date
}

struct Magazine {
let publishedDate: Date
}

enum StitchItem {
case book(Book)
case magazine(Magazine)
}

func stitch(_ books: [Book], magazines: [Magazine]) -> [StitchItem] {
let items = books.map({ StitchItem.book($0) }) + magazines.map({ StitchItem.magazine($0) })
return items.sorted(by: { book, magazine in
switch (book, magazine) {
case let (.book(b1), .book(b2)):
return b1.preferredOrder < b2.preferredOrder
case let (.book(book), .magazine(magazine)):
if book.publishedDate == magazine.publishedDate {
return true
} else {
return book.publishedDate < magazine.publishedDate
}
case let (.magazine(magazine), .book(book)):
if book.publishedDate == magazine.publishedDate {
return false
} else {
return book.publishedDate < magazine.publishedDate
}
case let (.magazine(m1), .magazine(m2)):
return m1.publishedDate < m2.publishedDate
}
})
}

The above sort function declares the intention but Swift just sort instead of trying to fully meet our requirements.

A manual solution is to sort each array first then use while loop to insert.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
func stitch(_ books: [Book], magazines: [Magazine]) -> [StitchItem] {
let books = books
.sorted(by: { $0.preferredOrder < $1.preferredOrder })
let magazines = magazines
.sorted(by: sortmagazines)

var bookIndex = 0
var magazineIndex = 0
var results: [StitchItem] = []
while (bookIndex < books.count && magazineIndex < magazines.count) {
let book = books[bookIndex]
let magazine = magazines[magazineIndex]
if book.publishedDate < magazine.publishedDate {
results.append(StitchItem.book(book))
bookIndex += 1
} else {
results.append(StitchItem.magazine(magazine))
magazineIndex += 1
}
}

while (bookIndex < books.count) {
let book = books[bookIndex]
results.append(StitchItem.book(book))
bookIndex += 1
}

while (magazineIndex < magazines.count) {
let magazine = magazines[magazineIndex]
results.append(StitchItem.magazine(magazine))
magazineIndex += 1
}

return results
}

How to make dynamic font size for UIButton

Issue #671

Use adjustsFontForContentSizeCategory

A Boolean that indicates whether the object automatically updates its font when the device’s content size category changes.

If you set this property to YES, the element adjusts for a new content size category on a UIContentSizeCategoryDidChangeNotification.

1
2
3
4
5
6
7
button.titleLabel?.adjustsFontForContentSizeCategory = true
button.backgroundColor = UIColor.green
button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .title1)

label.adjustsFontForContentSizeCategory = true
label.backgroundColor = UIColor.yellow
label.font = UIFont.preferredFont(forTextStyle: .title1)

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.

How to test for view disappear in navigation controller

Issue #670

To test for viewWillDisappear during UINavigationController popViewController in unit test, we need to simulate UIWindow so view appearance works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
final class PopTests: XCTestCase {
func testPop() {
let window = UIWindow(frame: UIScreen.main.bounds)
let navigationController = UINavigationController()
window.rootViewController = navigationController
let viewController = DetailViewController()

navigationController.viewControllers = [
UIViewController(),
viewController
]

window.makeKeyAndVisible()
let expectation = XCTestExpectation()
navigationController.popViewController(animated: false)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
XCTAssertTrue(viewController.wasDismissed)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
}
}
1
2
3
4
5
6
7
8
class DetailViewController: UIViewController {
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if isMovingFromParent {
wasDismissed = true
}
}
}

How to use useEffect in React hook

Issue #669

Specify params as array [year, id], not object {year, id}

1
2
3
4
5
6
7
8
9
10
11
12
13
const { year, id } = props
useEffect(() => {
const loadData = async () => {
try {

} catch (error) {
console.log(error)
}
}

listenChats()
}, [year, id])
}

Hooks effect

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

How to sign in with apple for web with firebase

Issue #668

Authenticate Using Apple with JavaScript

Use Firebase JS SDK

Configure Sign in with Apple for the web

Go to Certificates, Identifiers & Profiles -> Identifier create 2 ids: App ID and Service ID

For example: I have App ID com.onmyway133.myapp and Service ID com.onmyway133.myweb

Screenshot 2020-06-16 at 09 20 34

Remember that to view App ID or Service ID, there’s dropdown menu on the right

Screenshot 2020-06-16 at 09 21 20

For App ID, enable

  • Associated Domains
  • Sign In with Apple: Enable it as Primary App ID

For Service ID, use firebase callback url

Associate domain

Add apple-app-site-association in public folder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"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

Screenshot 2020-06-16 at 09 24 05

Configure in Firebase

Go to Sign in providers and enable Apple sign in.

Fill in

  • Service ID identifier (com.onmyway133.myweb)
  • OAuth code flow configuration: fill in your team id, key id and key secret content.
Screenshot 2020-06-16 at 09 25 23

How to use firebase cloud functions

Issue #667

Use node 10

Edit package.json

1
2
3
"engines": {
"node": "10"
},

Secret key

Go to settings/serviceaccounts/adminsdk, download secret key in form of json and place it in lib/config.json

1
2
3
4
5
6
const serviceAccount = require('./config.json')

admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://my-app-4b968.firebaseio.com"
})

Local serve

This builds and spins up emulator to test

1
npm run serve

CORS

1
response.set('Access-Control-Allow-Origin', '*');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var cors = require('cors');

// my function
var helloFn = function helloFn(req, res) {
res.status(200)
.send('Hello, Functions\n');
};

// CORS and Cloud Functions export logic
exports.hello = function hello(req, res) {
var corsFn = cors();
corsFn(req, res, function() {
helloFn(req, res);
});
}

How to go back to home in React

Issue #665

Usually in header we have logo that takes user back to the home page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// index.js
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from 'react-router-dom'

<Router>
<Switch>
<Route exact path="/">
<Home />
</Route>
</Router>
1
2
3
4
5
6
7
8
// Header.js

import { useHistory } from 'react-router-dom'
const history = useHistory()

<a class="navbar-item" onClick={() => {
history.push('/')
}}>

How to style video js

Issue #663

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/** @jsx jsx */
import { css, jsx } from '@emotion/core'
import React from 'react';
import videojs from 'video.js'

export default class VideoPlayer extends React.Component {
componentDidMount() {
// instantiate Video.js
this.player = videojs(this.videoNode, this.props, function onPlayerReady() {
console.log('onPlayerReady', this)
});
}

// destroy player on unmount
componentWillUnmount() {
if (this.player) {
this.player.dispose()
}
}

// wrap the player in a div with a `data-vjs-player` attribute
// so videojs won't create additional wrapper in the DOM
// see https://github.com/videojs/video.js/pull/3856
render() {
return (
<div>
<div data-vjs-player css={css`

`}>
<video
ref={node => this.videoNode = node}
className="video-js vjs-big-play-centered"
data-setup='{ "playbackRates": [0.5, 1, 1.5, 2] }'
css={css`
width: auto;
height: 400px;
`}>

</video>
</div>
</div>
)
}
}

How to use setState in React

Issue #662

Use spread operator

1
2
3
4
5
6
7
8
9
10
11
12
13
import React, { Component, useState, useEffect } from 'react';

const [state, setState] = useState({
message: '',
chats: [],
sending: false
})

setState(prevState => ({
...prevState,
message: '',
sending: false
}))

How to handle events for input with React

Issue #661

Use Bulma css

1
2
3
4
5
6
7
8
9
10
11
12
<input
class="input is-rounded"
type="text"
placeholder="Say something"
value={value}
onChange={(e) => { onValueChange(e.target.value) }}
onKeyDown={(e) => {
if (e.key === 'Enter') {
onSend(e)
}
}}
/>

How to handle evens in put with React

Issue #661

Use Bulma css

1
2
3
4
5
6
7
8
9
10
11
12
<input
class="input is-rounded"
type="text"
placeholder="Say something"
value={value}
onChange={(e) => { onValueChange(e.target.value) }}
onKeyDown={(e) => {
if (e.key === 'Enter') {
onSend(e)
}
}}
/>

How to set text color for UIDatePicker

Issue #660

Apply tintColor does not seem to have effect.

1
2
datePicker.setValue(UIColor.label, forKeyPath: "textColor")
datePicker.setValue(false, forKey: "highlightsToday")

How to auto scroll to top in react router 5

Issue #659

Use useLocation https://reacttraining.com/react-router/web/guides/scroll-restoration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import React, { useEffect } from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useLocation,
withRouter
} from 'react-router-dom'

function _ScrollToTop(props) {
const { pathname } = useLocation();

useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);

return props.children
}

const ScrollToTop = withRouter(_ScrollToTop)

function App() {
return (
<div>
<Router>
<ScrollToTop>
<Header />
<Content />
<Footer />
</ScrollToTop>
</Router>
</div>
)
}

How to use dynamic route in react router 5

Issue #658

Declare routes, use exact to match exact path as finding route is from top to bottom. For dynamic route, I find that we need to use render and pass the props manually.

Declare Router as the rooter with Header, Content and Footer. Inside Content there is the Switch, so header and footer stay the same across pages

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from 'react-router-dom'

function Content() {
return (
<Switch>
<Route exact path="/about">
<About />
</Route>
<Route exact path="/">
<Home />
</Route>
<Route path='/book/:id' render={(props) => {
return ( <BookDetail {...props } /> )
}} />
<Route>
<NotFound />
</Route>
</Switch>
)
}

function App() {
return (
<div>
<Router>
<Header />
<Content />
<Footer />
</Router>
</div>
)
}

To trigger route request, use useHistory hook. Note that we need to declare variable, and not use useHistory().push directly

1
2
3
4
5
6
7
import { useHistory } from 'react-router-dom'

const history = useHistory()

<a onClick={() => {
history.push(`/book/${uuid}`)
}} >

To get parameters, use match

1
2
3
4
5
6
7
8
export default function BookDetail(props) {
const [ state, setState ] = useState({
book: null
})

const { match } = props
// match.params.id
}

How to use folder as local npm package

Issue #657

Add library folder src/library

1
2
3
4
5
6
7
src
library
res.js
screens
Home
index.js
package.json

Declare package.json in library folder

1
2
3
4
{
"name": "library",
"version": "0.0.1"
}

Declare library as dependency in root package.json

1
2
3
"dependencies": {
"library": "file:src/library"
},

Now import like normal, for example in src/screens/Home/index.js

1
import res from 'library/res'

How to make switch statement in SwiftUI

Issue #656

Lately I’ve been challenging myself to declare switch statement in SwiftUI, or in a more generalized way, execute any anonymous function that can return a View

Use Switch and Case views

Note that this approach does not work yet, as TupeView should support variadic number of contents, and also T.RawValue needs to conform to Equatable in order to check the cases.

Also in Switch statement, Content can’t be inferred

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
struct Case<T: RawRepresentable, Content: View>: View {
let value: T
let content: Content

init(_ value: T, @ViewBuilder content: () -> Content) {
self.value = value
self.content = content()
}

var body: some View {
content
}
}

struct Switch<T: RawRepresentable, Content: View>: View {
let value: T
let cases: TupleView<Case<T, Content>>

init(_ value: T, @ViewBuilder cases: () -> TupleView<Case<T, Content>>) {
self.value = value
self.cases = cases()
}

var body: some View {
makeBody()
}

private func makeBody() -> some View {
// TODO: Logic here
cases
}
}

struct UseSwitchStatement {
let animal: Animal = .cat

var body: some View {
VStack {
Switch(animal) {
Case(Animal.cat) {
Text("cat")
}
Case(Animal.dog) {
Text("dog")
}
Case(Animal.mouse) {
Text("mouse")
}
}
}
}
}

Use MakeView

Another solution is to use a MakeView view, this is more generic as it can execute any functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
enum Animal: String {
case cat
case dog
case mouse
}

struct MakeView: View {
let make: () -> AnyView

var body: some View {
make()
}
}

struct UseMakeView: View {
let animal: Animal = .cat

var body: some View {
MakeView {
switch self.animal {
case .cat:
return Text("cat").erase()
case .dog:
return Text("dog").erase()
case .mouse:
return Text("mouse").erase()
}
}
}
}

How to update multiple state properties with React hooks

Issue #655

Declare state and setState

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
export default function Showcase(props) {
const factory = props.factory
const [state, setState] = useState(
{
factory,
selectedFilter: { name: '' }
}
)

const onFilterClick = (filter) => {
setState({
selectedFilter: filter,
factory: factory.filter((app) => {
return app.showcase.platforms.includes(filter.name)
})
})
}

let cards = state.factory.map((app, index) => {
return (
<Card app={app} key={app.slug} />
)
})

return (
<div>
<FilterBar onClick={onFilterClick} />
<div css={css`
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
margin: 0 auto;
padding: 0 8vw;
`}>
{cards}
</div>
</div>

)
}