How to use OSLog and OSLogStore in Swift

Issue #970 We can use Logger to log and OSLogStore to retrieve logs import OSLog import ReuseAcross final class LogService { static let shared = LogService() let logger = Logger( subsystem: "com.example.myapp", category: "Log" ) func export() -> [String] { do { let store = try OSLogStore(scope: .currentProcessIdentifier) let position = store.position(timeIntervalSinceLatestBoot: 1) let logs = try store .getEntries(at: position) .compactMap { $0 as? OSLogEntryLog } .filter { $0.subsystem == Bundle....

February 8, 2024 · 1 min · Khoa Pham

How to escape characters in json and regex with Swift string

Issue #963 In the world of Swift programming, we often come across situations where we need to work with string literals that contain special characters. These characters can include new lines, tabs, backslashes, and quotes — all of which need to be handled appropriately to ensure they don’t inadvertently affect the structure or behavior of our code. Traditionally, we negate their special meaning by escaping them with backslashes. However, Swift provides an even simpler method — raw strings....

January 12, 2024 · 4 min · Khoa Pham

How to use nextjs Image

Issue #962 Fill parent div A boolean that causes the image to fill the parent element, which is useful when the width and height are unknown. The parent element must assign position: “relative”, position: “fixed”, or position: “absolute” style. <div className="relative"> <Image src="" alt="" fill objectFit="cover" /> </div>

January 7, 2024 · 1 min · Khoa Pham

How to check NSTextField is first responder

Issue #961 NSTextField uses NSFieldEditor under the hood, you can check currentEditor if it is the firstResponder extension NSTextField { var isFirstResponder: Bool { currentEditor() == window?.firstResponder } }

January 7, 2024 · 1 min · Khoa Pham

Building an iOS camera calculator with Core ML’s Vision and Tesseract OCR

Issue #960 Also written on Fritz Math might be scary, but it’s an essential part of everyday life. Wouldn’t it be cool if we could build an app, point our phone’s camera at an expression, and let the app compute the result? Whenever I’ve needed to use math, I’ve wished this was possible. Now, with advances in machine learning and vision recognition in iOS, this is doable. In this guide, I’ll provide some of the technical details for working with Vision in iOS, as well as my personal experiences using this technology....

December 31, 2023 · 12 min · Khoa Pham

How to decode dynamic JSON key with JSONDecoder

Issue #959 Decoding JSON in Swift is most of the time very straightforward with help of Codable protocol and JSONDecoder. Sometimes the json contains dynamic key, like { "shipmunk": { "name": "Shipmunk", "link": "https://indiegoodies.com/shipmunk" }, "pastepal": { "name": "PastePal", "link": "https://indiegoodies.com/pastepal" }, "codelime": { "name": "Codelime", "link": "https://indiegoodies.com/codelime" } } Decoding JSON with dynamic keys in Swift can be tricky because the keys in your data can change, and Swift likes to know exactly what it’s working with ahead of time....

December 21, 2023 · 2 min · Khoa Pham

How to bundle js for use in JavaScriptCore in Swift

Issue #958 We can use any bundler, like Parcel, Webpack or Vite. Here I use Webpack 5 Install Webpack and Babel npm install @babel/polyfill webpack webpack-cli --save-dev @babel/polyfill is a package provided by Babel, a popular JavaScript compiler. The polyfill is a way to bring modern JavaScript features and APIs to older browsers that don’t support them natively. Before ES6 (ECMAScript 2015), JavaScript lacked many features that are now considered standard....

December 7, 2023 · 2 min · Khoa Pham

How to handle log in JSContext with JavascriptCore

Issue #957 Define console object and set log function to point to our Swift function import JavaScriptCore extension JSContext { func injectConsoleLog() { evaluateScript( """ var console = {}; """ ) let consoleLog: @convention(block) (Any) -> Void = { print($0) } objectForKeyedSubscript("console") .setObject(consoleLog, forKeyedSubscript: "log" as NSString) } } Then we can just call let context = JSContext()! context.injectConsoleLog() context.evaluateScript(jsContent)

December 7, 2023 · 1 min · Khoa Pham

Apple Developer Learning resources

Issue #955 Besides WWDC videos & documentation, Apple also has interactive tutorials and books. Below are some of my favorites learning resources Tutorials Introducing SwiftUI: SwiftUI is a modern way to declare user interfaces for any Apple platform. Create beautiful, dynamic apps faster than ever before. Develop apps for iOS: Learn the basics of Xcode, SwiftUI, and UIKit to create compelling iOS apps. Develop in Swift: Develop in Swift Tutorials are a great first step toward a career in app development using Xcode, Swift, and SwiftUI....

November 29, 2023 · 1 min · Khoa Pham

How to show anchor bottom view in SwiftUI

Issue #954 From iOS 15, there’s a handy safeAreaInset that allows us to place additional content extending the safe area. Shows the specified content beside the modified view. safeAreaInset allows us to customize which edge and alignment we can place our views. This works for both ScrollView, List and Form and you can apply it multiple times. The content view is anchored to the specified horizontal edge in the parent view, aligning its vertical axis to the specified alignment guide....

November 22, 2023 · 2 min · Khoa Pham

How to store Codable in AppStorage

Issue #949 AppStorage and SceneStorage accepts RawRepresentable where value is Int or String. Creates a property that can read and write to a string user default, transforming that to RawRepresentable data type. init(wrappedValue:_:store:) init( wrappedValue: Value, _ key: String, store: UserDefaults? = nil ) where Value : RawRepresentable, Value.RawValue == String One clever thing (that does not work) is to use a custom Codable type that conforms to RawRepresentable, like below...

October 3, 2023 · 2 min · Khoa Pham

How to update widget for iOS 17

Issue #948 iOS 17 has a new Stand by mode so SwiftUI introduces containerBackground for the system to decide when to draw background. It also automatically applies margin to widget so we may need to disable that To update existing widgets, we can write some useful extension extension View { @ViewBuilder func safeContainerBackground(@ViewBuilder content: () -> some View) -> some View { if #available(iOS 17.0, *) { self.containerBackground(for: .widget, content: content) } else { self....

October 2, 2023 · 1 min · Khoa Pham

How to force localized language with SwiftGen

Issue #945 The default SwiftGen generate generated strings L10n file like this extension L10n { private static func tr(_ table: String, _ key: String, _ args: CVarArg..., fallback value: String) -> String { let format = BundleToken.bundle.localizedString(forKey: key, value: value, table: table) return String(format: format, locale: Locale.current, arguments: args) } } // swiftlint:disable convenience_type private final class BundleToken { static let bundle: Bundle = { #if SWIFT_PACKAGE return Bundle.module #else return Bundle(for: BundleToken....

August 26, 2023 · 1 min · Khoa Pham

How to make tag flow layout using Layout protocol in SwiftUI

Issue #944 SwiftUI in iOS 16 supports Layout protocol to arrange subviews We need to implement 2 methods sizeThatFits(proposal:subviews:cache:) reports the size of the composite layout view. placeSubviews(in:proposal:subviews:cache:) assigns positions to the container’s subviews. We will make a custom layout that arranges elements from top leading and span element to new rows if it can’t fit the current row. Start by defining a FlowLayout struct that conforms to Layout protocol....

August 22, 2023 · 3 min · Khoa Pham

How to use hover annotation in Swift Charts

Issue #943 In this tutorial, we’ll learn how to use Swift Charts to visualize ranking data. We use default AxisMarks and AxisMarks to let Swift Charts interpolate x and y grid lines. For y axis, I want to have finer grain control over the grid, so I specify an arrayLiteral Note that for rank, the lower value the better ranking, so we make use of chartYScale with reversed automatic domain to flip from 0 -> 100 to 100 -> 0...

August 18, 2023 · 2 min · Khoa Pham

How to scale image fill without affect layout in SwiftUI

Issue #939 Instead of letting the Image decide the size, we can put it as background or overlay. I use clipped and contentShape to avoid the fill image obscuring touch event Color.clear .frame(height: 100) .overlay { AsyncImage(url: item.imageUrl) { image in image .resizable() .scaledToFill() } placeholder: { ProgressView() } } .clipped() .contentShape(Rectangle())

July 30, 2023 · 1 min · Khoa Pham

How to move Core Data database to AppGroup folder

Issue #938 To let app and extension to talk to the same database, we need to use AppGroup. Here is how to use replacePersistentStore Replaces one persistent store with another actor DatabaseMigrator { @AppStorage("DatabaseMigrator.hasMigrated") var hasMigrated = false func migrateIfNeeded() { guard !hasMigrated else { return } migrate() hasMigrated = true } private func migrate() { let oldContainer = NSPersistentCloudKitContainer(name: "Bookmarks") guard let oldStoreUrl = oldContainer.persistentStoreDescriptions.first?.url, let newStoreUrl = Constants....

July 30, 2023 · 1 min · Khoa Pham

How to read write files to iCloud Drive

Issue #937 First, you need to enable iCloud Documents capability. Go to target settings -> Signing & Capabilities -> iCloud ` Then inside your Info.plist, add this with your iCloud identifier and app name <key>NSUbiquitousContainers</key> <dict> <key>iCloud.com.onmyway133.PastePal</key> <dict> <key>NSUbiquitousContainerIsDocumentScopePublic</key> <true/> <key>NSUbiquitousContainerName</key> <string>PastePal</string> <key>NSUbiquitousContainerSupportedFolderLevels</key> <string>Any</string> </dict> </dict> To access to your iCloud Drive folder, we use FileManager to retrieve the folder. Returns the URL for the iCloud container associated with the specified identifier and establishes access to that container....

July 28, 2023 · 2 min · Khoa Pham

How to use keychain in Swift

Issue #934 There are a few keychain wrappers around but for simple needs, you can write it yourself Here is a basic implementation. I use actor to go with async/await, and a struct KeychainError to contain status code in case we want to deal with error cases. accessGroup is to define kSecAttrAccessGroup to share keychain across your apps public actor Keychain { public struct KeychainError: Error { let status: OSStatus } let service: String let accessGroup: String?...

July 20, 2023 · 2 min · Khoa Pham

How to make share and action extension in iOS

Issue #932 Add Share extension and Action extension respectively in Xcode. We can use the same code to both extension SwiftUI I usually make a ShareView in SwiftUI with ShareViewModel to control the logic struct ShareView: View { @ObservedObject var vm: ShareViewModel var body: some View { NavigationStack(path: $vm.routes) { List {} } } } In ShareViewController, we can just conform to UIViewController and add our SwiftUI view as child view controller...

July 12, 2023 · 2 min · Khoa Pham