How to cancel DispatchWorkItem and NSOperation

Issue #194 DispatchWorkItem https://stackoverflow.com/questions/48844169/swift-ios-dispatchworkitem-is-still-running-even-though-its-getting-cancelled https://stackoverflow.com/questions/29492707/how-to-stop-cancel-suspend-resume-tasks-on-gcd-queue NSOperation https://developer.apple.com/documentation/foundation/nsoperation/1411672-cancel?language=objc Grand Central Dispatch vs NSOperation https://stackoverflow.com/questions/43226434/2017-swift-3-1-gcd-vs-nsoperation https://medium.com/@johnsundell/a-deep-dive-into-grand-central-dispatch-in-swift-dead7f6e1ca7

April 3, 2019 · 1 min · 14 words · Khoa

How to construct URL with URLComponents and appendPathComponent in Swift

Issue #193 var components = URLComponents(string: "https://google.com/") components?.path = "abc/" components?.url -> nil var components = URLComponents(string: "https://google.com/") components?.path = "/abc/" components?.url components?.queryItems = [URLQueryItem(name: "q", value: "pokemon")] -> https://google.com/abc/?q=pokemon var url = URL(string: "https://google.com/") url?.appendPathComponent("/abc?q=pokemon") url -> https://google.com//abc%3Fq=pokemon

March 29, 2019 · 1 min · 39 words · Khoa

Curry in Swift and Javascript

Issue #185 You may encounter curry in everyday code without knowing it. Here is a bit of my reflections on curry and how to apply it in Javascript and Swift. Taking one parameter in Haskell In Haskell, all function officially takes only 1 parameter. Function with many parameters are just curried, which means they will be partially applied. Calling sum 1 just returns a function with 1 parameter, then 2is passed into this function....

March 24, 2019 · 6 min · 1129 words · Khoa

How to run executable in macOS

Issue #176 Enable executable chmod +x executable Add executable file to target Use Process with correct launchPad import Foundation protocol TaskDelegate: class { func task(task: Task, didOutput string: String) func taskDidComplete(task: Task) } class Task { weak var delegate: TaskDelegate? let process = Process() func run(arguments: [String]) { DispatchQueue.background.async { let launchPath = Bundle.main.path(forResource: "executable", ofType: "")! self.run(launchPath: launchPath, arguments: arguments) } } func stop() { DispatchQueue.background.async { if self.process.isRunning { self....

March 19, 2019 · 1 min · 200 words · Khoa

How to print current directory using Process in macOS

Issue #175 let process = Process() process.launchPath = "/bin/pwd" process.arguments = [] Should be the same as FileManager.default.currentDirectoryPath

March 19, 2019 · 1 min · 18 words · Khoa

How to change NSTextField backgroundColor in NSPopover

Issue #174 Disable vibrancy mode of NSPopover let popover = NSPopover() popover.appearance = NSAppearance(named: NSAppearance.Name.aqua)

March 19, 2019 · 1 min · 15 words · Khoa

How to make scrollable vertical NSStackView

Issue #173 You might need to flip NSClipView import AppKit import Anchors import Omnia final class ScrollableStackView: NSView { final class FlippedClipView: NSClipView { override var isFlipped: Bool { return true } } override init(frame frameRect: NSRect) { super.init(frame: frameRect) setup() } required init?(coder decoder: NSCoder) { fatalError() } let stackView: NSStackView = withObject(NSStackView()) { $0.orientation = .vertical } private let scrollView: NSScrollView = NSScrollView() private func setup() { addSubview(scrollView) scrollView....

March 18, 2019 · 1 min · 109 words · Khoa

How to load top level view from xib in macOS

Issue #171 var views: NSArray? NSNib(nibNamed: NSNib.Name("ProfileView"), bundle: nil)?.instantiate(withOwner: nil, topLevelObjects: &views) let profileView = views!.compactMap({ $0 as? ProfileView }).first!

March 18, 2019 · 1 min · 20 words · Khoa

UITableViewCell and Model

Issue #154 The most common UI element in iOS is UITableView, and the most common task is to display the UITableViewCell using the model. Although the title specifies UITableViewCell, but the problem involves other views (UICollectionView, custom view, …) as well There are many debates about this, so here I want to make a summary, all in my opinion It started with UITableViewCell Is Not a Controller This article follows strict MVC and states we should not pass model object to cell and let cell manipulate directly on the model....

February 27, 2018 · 3 min · 571 words · Khoa

Learning from Open Source Generic Factory

Issue #148 From https://github.com/devxoul/Pure/blob/master/Sources/Pure/FactoryModule.swift public protocol FactoryModule: Module { /// A factory for `Self`. associatedtype Factory = Pure.Factory<Self> /// Creates an instance of a module with a dependency and a payload. init(dependency: Dependency, payload: Payload) } From https://github.com/devxoul/Pure/blob/master/Sources/Pure/Factory.swift open class Factory<Module: FactoryModule> { private let dependencyClosure: () -> Module.Dependency /// A static dependency of a module. open var dependency: Module.Dependency { return self.dependencyClosure() } /// Creates an instance of `Factory`. /// /// - parameter dependency: A static dependency which should be resolved in a composition root....

January 26, 2018 · 1 min · 163 words · Khoa

Using camelCase for abbreviations

Issue #147 Each language and platform has its own coding style guide. This goes true when it comes to abbreviations. I’ve had some debates about whether to use JSON or Json, URL or Url, HTTP or Http. I personally prefer camelCase, so I’m very happy to see that Kotlin is on my side. See Kotlin Style guide, I think this guide should be applied in other languages, such as Swift 😛...

January 26, 2018 · 2 min · 311 words · Khoa

How to use standalone UINavigationBar in iOS

Issue #144 There are times we want the same UIViewController to look good when it’s presented modally or pushed from UINavigationController stack. Take a look at BarcodeScanner and the PR https://github.com/hyperoslo/BarcodeScanner/pull/82 When it is presented, we need a header view so that we can show a title and a close button. We can create a custom HeaderView that inherits from UIView or either embed it in a UINavigationController before presenting....

January 10, 2018 · 3 min · 449 words · Khoa

How to generate QR code in AppKit

Issue #140 I need to generate QR code in https://github.com/onmyway133/AddressGenerator. Fortunately with CoreImage filter, it is very easy. Code is in Swift 4 import AppKit final class QRCodeGenerator { func generate(string: String, size: CGSize) -> NSImage? { guard let data = string.data(using: .utf8) else { return nil } // Filter guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil } filter.setValue(data, forKey: "inputMessage") filter.setValue("Q", forKey: "inputCorrectionLevel") // CIImage guard let ciImage = filter....

January 6, 2018 · 1 min · 113 words · Khoa

Hiding back button in navigation bar in iOS

Issue #137 Use a custom NavigationController import UIKit class NavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() navigationBar.tintColor = .white navigationBar.barStyle = .black navigationBar.isTranslucent = false } override func pushViewController(_ viewController: UIViewController, animated: Bool) { viewController.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) super.pushViewController(viewController, animated: animated) } }

January 4, 2018 · 1 min · 50 words · Khoa

Some Swift tips

Issue #136 Adding final https://gist.github.com/krzysztofzablocki/8c9a6c428cf5fcf19effca223a5548cd

January 3, 2018 · 1 min · 5 words · Khoa

How to make NSCollectionView programatically in Swift

Issue #131 Here’s how to create NSCollectionView programatically. We need to embed it inside NScrollView for scrolling to work. Code is in Swift 4 NSCollectionView let layout = NSCollectionViewFlowLayout() layout.minimumLineSpacing = 4 collectionView = NSCollectionView() collectionView.dataSource = self collectionView.delegate = self collectionView.collectionViewLayout = layout collectionView.allowsMultipleSelection = false collectionView.backgroundColors = [.clear] collectionView.isSelectable = true collectionView.register( Cell.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell") ) NScrollView scrollView = NSScrollView() scrollView.documentView = collectionView view.addSubview(scrollView) NSCollectionViewItem final class Cell: NSCollectionViewItem { let label = Label() let myImageView = NSImageView() override func loadView() { self....

December 21, 2017 · 2 min · 224 words · Khoa

UnsafePointer in Swift

Issue #130 Code is in Swift 4 Constructing UnsafeMutablePointer let byteCount = 32 let result = UnsafeMutablePointer<UInt8>.allocate(capacity: byteCount) Data to UnsafePointer extension Data { func toPointer() -> UnsafePointer<UInt8>? { let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: count) let stream = OutputStream(toBuffer: buffer, capacity: count) stream.open() withUnsafeBytes({ (p: UnsafePointer<UInt8>) -> Void in stream.write(p, maxLength: count) }) stream.close() return UnsafePointer<UInt8>(buffer) } } UnsafePointer to Data extension UnsafePointer { func toData() -> Data { return Data(bytes: UnsafeRawPointer(self), count: 32) } } Dealing with C API This is how to do keccak hash using C API from https://github....

December 20, 2017 · 1 min · 145 words · Khoa

How to prevent UIVisualEffectView crash

Issue #124 We all know that there’s a potential crash with UIVisualEffectView on iOS 11. The fix is to not add sub views directly to UIVisualEffectView, but to its contentView. So we should change effectView.addSubview(button) to effectView.contentView.addubView(button) Here we don’t need to perform iOS version check, because effectView.contentView works for any iOS versions. Potential cases for crashes Here are some cases you can potentially cause the crashes Strange namings Normally we name our UIVisualEffectView as blurView, effectView....

December 20, 2017 · 3 min · 439 words · Khoa

Hashable and Set in Swift

Issue #122 From Set You can create a set with any element type that conforms to the Hashable protocol. By default, most types in the standard library are hashable, including strings, numeric and Boolean types, enumeration cases without associated values, and even sets themselves. From Hashable The Hashable protocol inherits from the Equatable protocol, so you must also add an equal-to operator (==) function for your custom type. public protocol Hashable : Equatable { /// The hash value....

December 13, 2017 · 1 min · 118 words · Khoa

Generic declaration in Swift

Issue #121 These are different class DiffService<T: MKAnnotation & Equatable> class DiffService<T: MKAnnotation, Equatable>

December 13, 2017 · 1 min · 14 words · Khoa