My favorite WWDC videos

Issue #891 WWDC18 Designing Fluid Interfaces Testing Tips & Tricks WWDC22 The craft of SwiftUI API design: Progressive disclosure Writing for interfaces Read more

June 10, 2022 路 1 min 路 Khoa Pham

WWDC swiftui-lounge

Issue #890 In WWDC21, WWDC22 Apple provide a Slack channel for people to interact with Apple engineers in digital lounges. Here I note down some interesting Q&As WWDC22 What鈥檚 the difference between a custom ViewModifier vs View extension Q: What鈥檚 the difference between a custom ViewModifier (without DynamicProperty) that uses some built-in modifiers in body(content:), and a custom View extension func that just use those built-in modifiers? Similarly, what鈥檚 the difference between a custom ViewModifier with some DynamicProperty and a custom View with some DynamicProperty (also has a @ViewBuilder content property to receive content to modify) ?...

June 10, 2022 路 32 min 路 Khoa Pham

What's new in SwiftUI iOS 16 at WWDC22

Issue #889 What鈥檚 new in SwiftUI New EnvironmentValues TextField inside Alert List uses UICollectionView See gist ButtonStyle composition Section("Hashtags") { VStack(alignment: .leading) { HStack { Toggle("#Swiftastic", isOn: $swiftastic) Toggle("#WWParty", isOn: $wwdcParty) } HStack { Toggle("#OffTheCharts", isOn: $offTheCharts) Toggle("#OneMoreThing", isOn: $oneMoreThing) } } .toggleStyle(.button) .buttonStyle(.bordered) } Customize Charts struct MonthlySalesChart: View { var body: some View { Chart(data, id: \.month) { BarMark( x: .value("Month", $0.month, unit: .month), y: .value("Sales", $0.sales) ) } ....

June 9, 2022 路 5 min 路 Khoa Pham

How to use any vs some in Swift

Issue #888 Embrace Swift generics This generic pattern is really common, so there鈥檚 a simpler way to express it. Instead of writing a type parameter explicitly, we can express this abstract type in terms of the protocol conformance by writing 鈥渟ome Animal鈥. The 鈥渟ome鈥 in 鈥渟ome Animal鈥 indicates that there is a specific type that you鈥檙e working with. func feed<A>(animal: A) where A: Animal {} func feed(animal: some Animal) An abstract type that represents a placeholder for a specific concrete type is called an opaque type....

June 8, 2022 路 5 min 路 Khoa Pham

How to use Swift

Issue #887 What鈥檚 new

June 7, 2022 路 1 min 路 Khoa Pham

How to use SwiftUI

Issue #886 SwiftUI iOS 16 SwiftUI SwiftUI practices 8 Common SwiftUI Mistakes 鈥 and how to fix them! 5 Steps to Better SwiftUI Views SwiftUI tips and tricks SwiftUI Tips Tips thread Quick Friday tips Reference

June 7, 2022 路 1 min 路 Khoa Pham

How to convert NSImage to PNG Data

Issue #885 Create NSBitmapImageRep with preferred size and draw NSImage onto that. Need to construct NSBitmapImageRep specifically instead of using convenient initializers like NSBitmapImageRep(data:), NSBitmapImageRep(cgImage:) to avoid device dependant resolution issue. extension NSImage { func pngData( size: CGSize, imageInterpolation: NSImageInterpolation = .high ) -> Data? { guard let bitmap = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bitmapFormat: [], bytesPerRow: 0, bitsPerPixel: 0 ) else { return nil } bitmap....

June 6, 2022 路 1 min 路 Khoa Pham

How to get notification userInfo at launch

Issue #884 When user taps on push notification, depending on app state SceneDelegate Checking UIScene.ConnectionOptions.notificationResponse?.notification.request.content.userInfo in scene(_:willConnectTo:options:) app terminated: sometimes nil app in background: notification info UNUserNotificationCenter Checking UNNotificationResponse.notification.request.content.userInfo in userNotificationCenter(_:didReceive:withCompletionHandler:) app terminated: notification info app in background: notification info Read more

June 1, 2022 路 1 min 路 Khoa Pham

How SwiftUI works

Issue #883 Read more

May 31, 2022 路 1 min 路 Khoa Pham

How to use popover in SwiftUI

Issue #882 In SwiftUI, .popover shows as popover on Mac and iPad, but as .sheet on iPhone (compact size class) We can use minWidth, minHeight to specify sizes on Mac and iPad. On iPhone, we can check and wrap it inside NavigationView. Setting navigationTitle without being embedded in NavigationView has not effect `` .popover(isPresented: $showsEdit) { EditSnippetView( snippet: snippet ) .frame(minWidth: 300, alignment: .topLeading) .navigationTitle("Tags") .modifier( EmbedInNavigationModifier() ) }

May 29, 2022 路 1 min 路 Khoa Pham

How to select in List in SwiftUI

Issue #881 Specify optional value for List(selection:). This keeps selection on macOS, but not on iPad. On iPad each row in the List needs to be NavigationLink, no need for .tag. The selection is not updated, need to manually update with onTapGesture For List selection to work, make sure selection binding type matches. Preferablly using ID than Self Need to specify id in ForEach for List to infer tag. Otherwise, need to specify tag for cell struct Sidebaer: View { class ViewModel: ObservableObject { @Published var group: BookGroup?...

May 27, 2022 路 1 min 路 Khoa Pham

How to use native SSL Pinning

Issue #880 From iOS 14, we can do Identity Pinning: How to configure server certificates for your app right from Info.plist <key>NSAppTransportSecurity</key> <dict> <key>NSPinnedDomains</key> <dict> <key></key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSPinnedCAIdentities</key> <array> <dict> <key>SPKI-SHA256-BASE64</key> <string>12312312312xasdas123asdasdasdasdsad</string> </dict> </array> </dict> </dict> </dict> There are a few drawbacks The subdomains works for multiple part host as well, as long as it is 1 subdomain level Need to duplicate values in each Info.plist Need to duplicate values if the host differs Can鈥檛 use User Defined Settings variables in localized Info....

May 23, 2022 路 1 min 路 Khoa Pham

How to use NSPersistentCloudKitContainer

Issue #879 Setting Up Core Data with CloudKit Enable iCloud Enable CloudKit and Push Notifications Enable Remote Notifications in the Background Creating a Core Data Model for CloudKit Initialize Your CloudKit Schema During Development let container = NSPersistentCloudKitContainer(name: "Earthquakes") // Only initialize the schema when building the app with the // Debug build configuration. #if DEBUG do { // Use the container to initialize the development schema....

May 11, 2022 路 2 min 路 Khoa Pham

How to allow multiple selection in List in SwiftUI

Issue #878 Note that Explicit id is needed, although Book already conforms to Identifiable selection needs a default value class BookViewModel: ObservableObject { @Published var books: [Book] = [] @Published var selectedBooks: Set<Book> = [] } List(selection: $viewModel.selectedBooks) { ForEach(viewModel.books, id: \.self) { book in BookRow(book: book) } }

April 30, 2022 路 1 min 路 Khoa Pham

How to use ViewBuilder in SwiftUI

Issue #877 Over the course of making several SwiftUI apps, I鈥檝e discovered quite a few hidden magic of SwiftUI that are quite fun. Here are 6 interesting SwiftUI features in View Builder many don鈥檛 know are even possible 馃く View protocol with enum Struct is not the only way to describe #SwiftUI views. Learn how you can achieve the same thing with just enum Conform primitive type to View protocol You can also conform any value type or primitive type to View protocol...

April 11, 2022 路 2 min 路 Khoa Pham

How to debounce TextField search in SwiftUI

Issue #876 Make a dedicate DebounceObject to debounce (or throttle). Then we can even observe with onChange on the debouncedText or just use it directly to sort import Combine public final class DebounceObject: ObservableObject { @Published var text: String = "" @Published var debouncedText: String = "" private var bag = Set<AnyCancellable>() public init(dueTime: TimeInterval = 0.5) { $text .removeDuplicates() .debounce(for: .seconds(dueTime), scheduler: DispatchQueue.main) .sink(receiveValue: { [weak self] value in self?...

March 26, 2022 路 1 min 路 Khoa Pham

How to create document based macOS app

Issue #875 Read newDocument This method calls openUntitledDocumentAndDisplay(_:). Read openUntitledDocumentAndDisplay The default implementation of this method calls defaultType to determine the type of new document to create, calls makeUntitledDocument(ofType:) to create it, then calls addDocument(_:) to record its opening. Read defaultType The default implementation of this method returns the first Editor type declared by the CFBundleDocumentTypes array in the application鈥檚 Info.plist, or returns nil if no Editor type is declared....

March 19, 2022 路 1 min 路 Khoa Pham

How to add dot indicator to tab bar item in iOS

Issue #874 From iOS 13, use UITabBarAppearance and UITabBarItemAppearance let appearance = UITabBarAppearance() let itemAppearance = UITabBarItemAppearance(style: .stacked) itemAppearance.normal.badgeBackgroundColor = .clear itemAppearance.normal.badgeTextAttributes = [.foregroundColor:] profileViewController.tabBarItem.badgeValue = "鈼" Read more

March 15, 2022 路 1 min 路 Khoa Pham

How to use Multipeer Connectivity

Issue #873 Use assistant let assistant = MCAdvertiserAssistant(serviceType: "my-service, discoveryInfo: nil, session: mcSession) assistant.start() let browser = MCBrowserViewController(serviceType: "my-service", session: mcSession) browser.delegate = self present(browser, animated: true) Manual let advertiser = MCNearbyServiceAdvertiser(peer: localPeerID, discoveryInfo: nil, serviceType: self.serviceType) advertiser.startAdvertisingPeer() let browser = MCNearbyServiceBrowser(peer: localPeerID, serviceType: self.serviceType) browser.startBrowsingForPeers() Enable in Info.plist <key>NSLocalNetworkUsageDescription</key> <string>Enable local network discovery to use Peer Share</string> <key>NSBonjourServices</key> <array> <string>_my-service._tcp</string> <string>_my-service._udp</string> </array> Read more

March 15, 2022 路 1 min 路 Khoa Pham

How to generate Polygon wallet account in Swift

Issue #871 Use libraries import web3 import web3keystore import KeychainAccess private final class KeyStorage: EthereumKeyStorageProtocol { enum Key: String { case privateKey case phrase } private let keychain = Keychain(service: "com.example.myapp") func storePrivateKey(key: Data) throws { try keychain.set(key, key: Key.privateKey.rawValue) } func loadPrivateKey() throws -> Data { if let data = try keychain.getData(Key.privateKey.rawValue) { return data } else { throw EthereumKeyStorageError.failedToLoad } } var phrase: String? { get { try?...

February 24, 2022 路 2 min 路 Khoa Pham