How to make simple tracker via swizzling in Swift

Issue #568 Code EasyTracker Swizzle viewDidAppear https://github.com/onmyway133/EasyTracker/blob/master/Sources/Trackers.swift import UIKit var mapping: [String: (UIViewController) -> Void] = [:] var hasSwizzled = false public func track<T: UIViewController>(_ type: T.Type, block: @escaping (T) -> Void) { let original = #selector(UIViewController.viewDidAppear(_:)) let swizled = #selector(UIViewController.trackers_viewDidAppear(_:)) if !hasSwizzled { swizzle(kClass: UIViewController.self, originalSelector: original, swizzledSelector: swizled) hasSwizzled = true } mapping[NSStringFromClass(type)] = { controller in if let controller = controller as? T { block(controller) } } } extension UIViewController { func trackers_viewDidAppear(_ animated: Bool) { trackers_viewDidAppear(animated) let string = NSStringFromClass(type(of: self)) mapping[string]?...

January 4, 2020 · 1 min · Khoa Pham

How to make simple adapter for delegate and datasource for UICollectionView and UITableView

Issue #567 Code Upstream Make open Adapter https://github.com/onmyway133/Upstream import UIKit public protocol AdapterDelegate: class { /// Apply model to view func configure(model: Any, view: UIView, indexPath: IndexPath) /// Handle view selection func select(model: Any) /// Size the view func size(model: Any, containerSize: CGSize) -> CGSize } /// Act as DataSource and Delegate for UICollectionView, UITableView open class Adapter: NSObject, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITableViewDataSource, UITableViewDelegate { public var sections: [Section] = [] public weak var collectionView: UICollectionView?...

January 4, 2020 · 5 min · Khoa Pham

How to make progress HUD in Swift

Issue #566 Code FantasticDisplay Create a container that has blur effect public class HUDContainer: UIVisualEffectView, AnimationAware { private let innerContentView: UIView & AnimationAware public let label = UILabel() public var text: String? { didSet { label.text = text label.sizeToFit() label.isHidden = text == nil } } public init(contentView: UIView & AnimationAware) { self.innerContentView = contentView super.init(effect: UIBlurEffect(style: .light)) self.contentView.addSubview(innerContentView) self.contentView.addSubview(label) innerContentView.pinEdgesToSuperview() configure() } public required init?(coder aDecoder: NSCoder) { fatalError() } public func configure() { layer....

January 4, 2020 · 4 min · Khoa Pham

How to specify year in date formatter in Swift

Issue #565 Serious Security: The decade-ending Y2K bug that wasnt Challenges of DateFormatters

January 3, 2020 · 1 min · Khoa Pham

How to build static site using Publish

Issue #564 Code https://github.com/JohnSundell/publish Example https://github.com/pumaswift/pumaswift.github.io Steps Step 1: Create executable swift package init --type executable Step 2: Edit package // swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "PumaSwiftWeb", dependencies: [ .package(url: "https://github.com/johnsundell/publish.git", from: "0.1.0") ], targets: [ .target( name: "PumaSwiftWeb", dependencies: [ "Publish" ] ) ] ) Step 3: Double click Package.swift, Xcode opens that in a generated project Step 4: Declare website....

January 2, 2020 · 1 min · Khoa Pham

How to use iTMSTransporter

Issue #563 Transporter app Transporter Now Available on the Mac App Store The new Transporter app for macOS makes it easy to upload your binary to App Store Connect. To get started, download Transporter from the Mac App Store, and simply drag and drop your binaries into the upload window. With Transporter you can https://stackoverflow.com/questions/8094317/where-to-find-application-loader-app-in-mac/40419328 As of Xcode 11, "Application Loader is no longer included with Xcode", per the Xcode 11 Release Notes: Xcode supports uploading apps from the Organizer window or from the command line with xcodebuild or xcrun altool....

January 1, 2020 · 3 min · Khoa Pham

How to use Timer and RunLoop in Swift

Issue #562 Run Timer in command line application Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { _ in completion(.success(())) }) RunLoop.current.run() Read more https://www.hackingwithswift.com/articles/117/the-ultimate-guide-to-timer https://learnappmaking.com/timer-swift-how-to/

January 1, 2020 · 1 min · Khoa Pham

How to use safeAreaInsets in iOS

Issue #561 Read more https://medium.com/rosberryapps/ios-safe-area-ca10e919526f https://blog.smartnsoft.com/layout-guide-margins-insets-and-safe-area-demystified-on-ios-10-11-d6e7246d7cb8 https://www.matrixprojects.net/p/safe-area-insets/ https://stackoverflow.com/questions/37796884/on-ios-what-are-the-differences-between-margins-edge-insets-content-insets-a/47614397

December 30, 2019 · 1 min · Khoa Pham

How to send message from bot to Slack in Swift

Issue #560 Create a bot https://slack.com/intl/en-no/help/articles/115005265703-create-a-bot-for-your-workspace https://api.slack.com/bot-users#setup-events-api https://api.slack.com/bot-users#installing-bot Post message After adding bot to workspace, we’ll get OAuth Access Token and Bot User OAuth Access Token. Use Bot User OAuth Access Token to test drive bot message sending https://api.slack.com/methods/chat.postMessage/test The request url is like https://slack.com/api/chat.postMessage?token=xoxb-7212342835698-890815481123-abcdGgDEFfm2joQs1Vj5mABC&channel=random&text=hello&pretty=1 Code from Puma import Foundation public class Slack { public var name: String = "Send message to Slack" public var isEnabled = true private var message: Message?...

December 30, 2019 · 2 min · Khoa Pham

How to parse xcrun simctl devices

Issue #559 public class GetDestinations { public init() {} public func getAvailable(workflow: Workflow) throws -> [Destination] { let processHandler = DefaultProcessHandler(filter: { $0.starts(with: "name=") }) let string = try CommandLine().runBash( workflow: workflow, program: "xcrun simctl", arguments: [ "list", "devices", "-j" ], processHandler: processHandler ) guard let data = string.data(using: .utf8) else { throw PumaError.invalid } let response: Response = try JSONDecoder().decode(Response.self, from: data) let devicesWithOS: [DeviceWithOS] = response.devices.flatMap({ key, value in return value....

December 28, 2019 · 2 min · Khoa Pham

How to parse xcrun instruments devices

Issue #558 public class GetDestinations { public init() {} public func getAvailable(workflow: Workflow) throws -> [Destination] { let processHandler = DefaultProcessHandler(filter: { $0.starts(with: "name=") }) let string = try CommandLine().runBash( workflow: workflow, program: "xcrun instruments", arguments: [ "-s", "devices" ], processHandler: processHandler ) // Ex: iPad Air (11.0.1) [7A5EAD29-D870-49FB-9A9B-C81079620AC9] (Simulator) let destinations: [Destination] = try string .split(separator: "\n") .map({ String($0) }) .filter({ try $0.hasPattern(pattern: #"\[.+\]"#) }) .compactMap({ (line) -> Destination? in parse(line) }) return destinations } func parse(_ line: String) -> Destination?...

December 28, 2019 · 2 min · Khoa Pham

How to use test environment variables with shared scheme in Xcode

Issue #557 Use ProcessInfo to access environment variables. ProcessInfo().environment["username"] Duplicate main shared scheme TestApp to TestAppWithCredentials, but don’t share this TestAppWithCredentials scheme

December 28, 2019 · 1 min · Khoa Pham

How to generate xml in Swift

Issue #556 Instead of learning XMLParser, we can make a lightweight version import Foundation public protocol XmlItem { func toLines() -> [String] } public struct XmlString: XmlItem { public let key: String public let value: String public init(key: String, value: String) { self.key = key self.value = value } public func toLines() -> [String] { return [ "<key>\(key)</key>", "<string>\(value)</string>" ] as [String] } } public struct XmlBool: XmlItem { public let key: String public let value: Bool public init(key: String, value: Bool) { self....

December 27, 2019 · 2 min · Khoa Pham

How to use synthetic property in Kotlin Android Extension

Issue #555 Synthetic properties generated by Kotlin Android Extensions plugin needs a view for Fragment/Activity to be set before hand. In your case, for Fragment, you need to use view.btn_K in onViewCreated override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val view = inflater.inflate(R.layout.fragment_card_selector, container, false) view.btn_K.setOnClickListener{} // access with `view` return view } Or better, you should only access synthetic properties in onViewCreated...

December 23, 2019 · 1 min · Khoa Pham

How to use KVO in Swift

Issue #554 A class must inherit from NSObject, and we have 3 ways to trigger property change Use setValue(value: AnyObject?, forKey key: String) from NSKeyValueCoding class MyObjectToObserve: NSObject { var myDate = NSDate() func updateDate() { setValue(NSDate(), forKey: "myDate") } } Use willChangeValueForKey and didChangeValueForKey from NSKeyValueObserving class MyObjectToObserve: NSObject { var myDate = NSDate() func updateDate() { willChangeValueForKey("myDate") myDate = NSDate() didChangeValueForKey("myDate") } } Use dynamic. See Swift Type Compatibility...

December 22, 2019 · 1 min · Khoa Pham

How to use precondition and assert in Swift

Issue #553 Read Swift asserts - the missing manual debug release release function -Onone -O -Ounchecked assert() YES NO NO assertionFailure() YES NO NO** precondition() YES YES NO preconditionFailure() YES YES YES** fatalError()* YES YES YES And from Interesting discussions on Swift Evolution – assert: checking your own code for internal errors – precondition: for checking that your clients have given you valid arguments. Read more https://stackoverflow....

December 22, 2019 · 1 min · Khoa Pham

How to get ISO string from date in Javascript

Issue #552 type Components = { day: number, month: number, year: number } export default class DateFormatter { // 2018-11-11T00:00:00 static ISOStringWithoutTimeZone = (date: Date): string => { const components = DateFormatter.format(DateFormatter.components(date)) return `${components.year}-${components.month}-${components.day}T00:00:00` } static format = (components: Components) => { return { day: `${components.day}`.padStart(2, '0'), month: `${components.month}`.padStart(2, '0'), year: components.year } } static components = (date: Date): Components => { return { day: date.getDate(), month: date.getMonth() + 1, year: date....

December 22, 2019 · 1 min · Khoa Pham

How to use regular expression in Swift

Issue #551 Find matches import Foundation public extension String { func matches(pattern: String) throws -> [String] { let regex = try NSRegularExpression(pattern: pattern) let results = regex.matches(in: self, options: [], range: NSRange(self.startIndex..., in: self)) return results.compactMap({ result in if let range = Range(result.range, in: self) { return String(self[range]) } else { return nil } }) } func hasPattern(pattern: String) throws -> Bool { return try !matches(pattern: pattern).isEmpty } } func testRegex() throws { let string = "iPad Air (11....

December 20, 2019 · 1 min · Khoa Pham

Why is didSelectItem not called in UICollectionView

Issue #550 Check shouldHighlightItem -> shouldSelectItem -> didSelectItem Gesture recognizer isUserInteractionEnabled

December 20, 2019 · 1 min · Khoa Pham

How to keep command line tool running with async in Swift

Issue #549 Use Semaphore public class Sequence: Task { public func run(workflow: Workflow, completion: @escaping TaskCompletion) { let semaphore = DispatchSemaphore(value: 0) runFirst(tasks: tasks, workflow: workflow, completion: { result in completion(result) semaphore.signal() }) semaphore.wait() } } public class Concurrent: Task { public func run(workflow: Workflow, completion: @escaping (Result<(), Error>) -> Void) { var runTaskCount = 0 let taskCount = tasks.count let semaphore = DispatchSemaphore(value: 0) tasks.forEach { task in task.run(workflow: workflow, completion: { _ in self....

December 18, 2019 · 1 min · Khoa Pham