onmyway133

Hi there, I’m Khoa aka onmyway133 👋

  • 🧑‍💻 I love crafting high quality and useful apps

  • 🔥 I love open source. My GitHub open source has 1.6k followers with packages that are integrated by 45k+ apps and over 3.4m+ downloads on CocoaPods.

  • ✍️ I write here on my blog and on Medium, which has over 2.4k+ followers with tons of articles and 90k+ monthly views.

  • 🖥 Follow me for sharings about Swift, SwiftUI, iOS and macOS development

How to fallback img in React

Issue #804 <img src={user.avatarUrl} onError={(e) => { e.target.onerror = null; e.target.src = "/images/default.png" }} /> Extract to React Component interface Props { src: string className: string fallback: string } export default function FallbackImg(props: Props) { return ( <img className={props.className} src={props.src} onError={(e) => { // @ts-ignore e.target.src = props.fallback }} /> ) } How to fallback backgroundImage Use 2 url var el = document.createElement('div') el.className = 'marker' el.style.backgroundImage = `url('${user.avatarUrl}'), url('/images/user....

May 26, 2021 · 1 min · Khoa Pham

How to use videojs in React

Issue #803 import React from 'react'; import videojs from 'video.js' import 'video.js/dist/video-js.css'; export default class VideoPlayer extends React.Component { createPlayer() { // instantiate Video.js this.player = videojs(this.videoNode, this.props, function onPlayerReady() { //console.log('onPlayerReady', this) }); } disposePlayer() { if (this.player) { this.player.dispose() } } componentDidMount() { this.createPlayer() } componentWillUnmount() { this.disposePlayer() } componentDidUpdate(prevProps) { if (this.props.sources != prevProps.sources) { this.player.src(this.props.sources[0]) } } // 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....

May 20, 2021 · 1 min · Khoa Pham

How to use FontAwesome 5 in Nextjs

Issue #802 npm i --save @fortawesome/fontawesome-svg-core \ @fortawesome/free-solid-svg-icons \ @fortawesome/free-brands-svg-icons \ @fortawesome/react-fontawesome import { faApple, faGithub, faTwitter } from '@fortawesome/free-brands-svg-icons' import { faUser, faPowerOff, faAngleDown } from '@fortawesome/free-solid-svg-icons' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' <FontAwesomeIcon icon={faCoffee} /> ...

May 19, 2021 · 1 min · Khoa Pham

How to use Bulma in Nextjs

Issue #801 Read https://nextjs.org/docs/basic-features/built-in-css-support#sass-support npm install bulma sass In styles/index.scss @import '~bulma/bulma'; In _app.tsx import '../styles/index.scss' ...

May 19, 2021 · 1 min · Khoa Pham

Recommended resource for learning SwiftUI

Issue #800 I’ve done some #SwiftUI lately for Push Hero and PastePal, and amazed by how easy and fun it is to make apps. If you want to get into SwiftUI but don’t know where to start, here are my recommended resources Twitter https://twitter.com/onmyway133/status/1359608162899415040 Thread reader https://threadreaderapp.com/thread/1359608162899415040.html...

April 30, 2021 · 1 min · Khoa Pham

How to make your apps stand out on the AppStore

Issue #799 Besides coming up with a good idea and building the app, there are many other things you can do to boost your apps' visibility Twitter thread https://twitter.com/onmyway133/status/1387851727714635776 Thread reader https://threadreaderapp.com/thread/1387851727714635776.html...

April 30, 2021 · 1 min · Khoa Pham

How to use SwiftGen and LocalizedStringKey in SwiftUI

Issue #798 swiftgen.yml strings: inputs: PastePal/Resources/Localizable/en.lproj outputs: - templatePath: swiftgen-swiftui-template.stencil output: PastePal/Resources/Strings.swift Template from https://github.com/SwiftGen/SwiftGen/issues/685 swiftgen-swiftui-template.stencil // Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen {% if tables.count > 0 %} import SwiftUI // MARK: - Strings {% macro parametersBlock types %}{% filter removeNewlines:"leading" %} {% for type in types %} {% if type == "String" %} _ p{{forloop.counter}}: Any {% else %} _ p{{forloop.counter}}: {{type}} {% endif %} {{ ", " if not forloop....

April 27, 2021 · 2 min · Khoa Pham

How to localize SwiftUI projects

Issue #797 Reference https://stackoverflow.com/questions/62092635/populating-localizable-strings-file-with-terminal-genstring-command-in-swiftui https://github.com/SwiftGen/SwiftGen https://stackoverflow.com/questions/46924196/localizable-strings-the-data-couldn-t-be-read-because-it-isn-t-in-the-correct ...

April 23, 2021 · 1 min · Khoa Pham

How to use ForEach with indices in SwiftUI

Issue #796 One seemingly obvious way to use ForEach on array with indices is using enumerated struct Book: Hashable, Identifiable { let id: UUID let name: String } struct BooksView: View { let books: [Book] var body: some View { List { ForEach(Array(books.enumerated()), id: \.element) { index, book in Text(book.name) .background(index % 2 == 0 ? Color.green : Color.orange) } } } } Reading the documentation for enumerated closely When you enumerate a collection, the integer part of each pair is a counter for the enumeration, but is not necessarily the index of the paired value....

April 20, 2021 · 2 min · Khoa Pham

How to resize NSImage with padding

Issue #795 extension NSImage { func resize(width: CGFloat, height: CGFloat, padding: CGFloat) -> NSImage { let img = NSImage(size: CGSize(width: width, height: height)) img.lockFocus() let ctx = NSGraphicsContext.current ctx?.imageInterpolation = .high self.draw( in: NSMakeRect(0, 0, width, height), from: NSMakeRect(0, -padding, size.width, size.height - padding), operation: .copy, fraction: 1 ) img.unlockFocus() return img } } So we can use like button.image = NSImage(named: NSImage.Name("pastePal"))?.resize(width: 22, height: 22, padding: -4) ...

April 15, 2021 · 1 min · Khoa Pham

How to convert from paid to freemium in SwiftUI with RevenueCat

Issue #794 I’ve been distributing my apps PastePal and Push Hero as a paid upfront apps on Appstore. I’ve quickly come to realize the importance of trials since many have requested a tryout before purchasing. Manual sending out trials comes with its own problem. I need to notarize and package the app as a dmg file, and not to even mention implement my own trial mechanism to check and notify of expired builds....

April 11, 2021 · 5 min · Khoa Pham

How to repeat array of object in Swift

Issue #793 To create array containing number of repeated value in Swift, we can use Array.init(repeating:count:) let fiveZs = Array(repeating: "Z", count: 5) print(fiveZs) // Prints "["Z", "Z", "Z", "Z", "Z"]" However, if we read Collection Types guide about Creating an Array with a Default Value Swift’s Array type also provides an initializer for creating an array of a certain size with all of its values set to the same default value....

March 22, 2021 · 2 min · Khoa Pham

How to use dynamic color in iOS

Issue #792 iOS 13 introduced Dark Mode with User Interface Style that makes it easy to support dark and light theme in our apps. Before we dive in, here are some official resources WWDC 2019 Implementing Dark Mode on iOS Supporting Dark Mode in Your Interface Choosing a Specific Interface Style for Your iOS App Adaptive color Like adaptive layout that adapts to different screen sizes, adaptive colors adapt to different user interface styles, for now they are light and dark mode....

March 13, 2021 · 7 min · Khoa Pham

How to use View protocol in SwiftUI

Issue #791 SwiftUI has View protocol which represents part of your app’s user interface and provides modifiers that you use to configure views. You create custom views by declaring types that conform to the View protocol. Implement the required body computed property to provide the content for your custom view. A typical example of View is using struct enum HeroType { case melee case range } struct ContentView: View { let heroType: HeroType var body: some View { switch heroType { case ....

March 10, 2021 · 1 min · Khoa Pham

How too save image to Photo library in iOS

Issue #790 Use UIImageWriteToSavedPhotosAlbum Adds the specified image to the user’s Camera Roll album. Let’s make an NSObject delegate class so we can perform target action to notify about completion import UIKit struct ImageService { final class Delegate: NSObject { let completion: (Error?) -> Void init(completion: @escaping (Error?) -> Void) { self.completion = completion } @objc func savedImage( _ im: UIImage, error: Error?, context: UnsafeMutableRawPointer? ) { DispatchQueue.main.async { self....

March 10, 2021 · 1 min · Khoa Pham

How to manage WindowGroup in SwiftUI for macOS

Issue #789 Using WindowGroup New in SwiftUI 2.0 for iOS 14 and macOS 11.0 is WindwGroup which is used in App protocol. WindowGroup is ideal for document based applications where you can open multiple windows for different content or files. For example if you’re developing a text editor or drawing apps, you can show multiple windows for different text file or drawing. All is handled automatically for you if you use WindowGroup...

March 7, 2021 · 6 min · Khoa Pham

How to show img tag from GitHub markdown in Hugo

Issue #788 I just convert my blog https://onmyway133.com/ from Hexo.js back to Hugo again. Hugo now uses goldmark as the default markdown processor instead of blackfriday All works well, except that I use GitHub markdown to write articles, which use raw HTML img tag for uploaded images. Hugo works well with ![]() syntax but it ignores img tag <img width="574" alt="Screenshot 2021-02-26 at 10 08 38" src="https://user-images.githubusercontent.com/2284279/109279894-99d09a80-781a-11eb-9d50-10f46ba94105.png"> The solution is to tell goldmark to accept raw HTML....

March 2, 2021 · 1 min · Khoa Pham

How to name Boolean property in Swift

Issue #787 In Swift, property, especially for Boolean flagging, uses the regular verb form for the third person. There are few exceptions, such as enable NSManagedObjectContext.automaticallyMergesChangesFromParent UIView.clipsToBounds UIView.translatesAutoresizingMaskIntoConstraints SwiftUI.Transaction.disablesAnimations UIScrollView.scrollsToTop NSView.isHidden UndoManager.enableUndoRegistration ...

February 28, 2021 · 1 min · Khoa Pham

How to use with block configure in Swift

Issue #786 Sometimes we need to update some properties between objects, for example book.name = updatedBook.name book.page = updatedBook.page book.publishedAt = updatedBook.publishedAt Repeating the caller book is tedious and error-prone. In Kotlin, there is with block which is handy to access the receiver properties and methods without referring to it. with(book) { name = updatedBook.name page = updatedBook.page publishedAt = updatedBook.publishedAt } In Swift, there are no such thing, we can write some extension like...

February 28, 2021 · 1 min · Khoa Pham

How to use Core Data

Issue #785 Core Data Responding to changes in a managed object context Calling mergeChanges on a managed object context will automatically refresh any managed objects that have changed. This ensures that your context always contains all the latest information. Note that you don’t have to call mergeChanges on a viewContext when you set its automaticallyMergesChangesFromParent property to true. In that case, Core Data will handle the merge on your behalf....

February 26, 2021 · 5 min · Khoa Pham