How to show full screen window programmatically in macOS

Issue #242 let window = NSWindow(contentRect: mainScreen.frame, styleMask: .borderless, backing: .buffered, defer: false) window.level = .floating window.contentView = NSView() window.makeKeyAndOrderFront(NSApp) NSApp.activate(ignoringOtherApps: true) and then later hide it window.orderOut(NSApp)

May 16, 2019 · 1 min · 28 words · Khoa

Useful git commands for everyday use!

Issue #239 Do you know that questions about git get the most views on StackOverflow? I’ve searched a lot on Google how to execute certain actions with git, and this actually slowed me down a lot. There are some actions that we tend to use a lot, so it’s good to learn them. Here are my favorites, learning from friends and internet, hope you find them useful. Before we begin, you should run git –version to check your current git version, mine is 2....

May 15, 2019 · 7 min · 1372 words · Khoa

How to work around app damaged warning in macOS

Issue #238 “App” is damaged and can’t be opened. You should move it to the Trash. 👉 Disable gate keeper sudo spctl --master-disable spctl --status Current workaround is to remove Launch At Login handling code.

May 15, 2019 · 1 min · 35 words · Khoa

How to fix UITargetAppPath should be provided in iOS tests

Issue #237 Go to test target, under Host Application, select another app target, and select the preferred app target again

May 15, 2019 · 1 min · 20 words · Khoa

How to shake NSView in macOS

Issue #233 Animation on macOS using CAAnimation Shake let midX = box.layer?.position.x ?? 0 let midY = box.layer?.position.y ?? 0 let animation = CABasicAnimation(keyPath: "position") animation.duration = 0.06 animation.repeatCount = 4 animation.autoreverses = true animation.fromValue = CGPoint(x: midX - 10, y: midY) animation.toValue = CGPoint(x: midX + 10, y: midY) box.layer?.add(animation, forKey: "position") Animation on macOS using NSAnimationContext Wiggle NSAnimationContext.runAnimationGroup({ context in let animation = CAKeyframeAnimation(keyPath: "transform") animation.beginTime = CACurrentMediaTime() + 5....

May 15, 2019 · 1 min · 145 words · Khoa

How to fit UIBezierPath in frame in iOS

Issue #232 From https://github.com/xhamr/paintcode-path-scale with some updates extension CGRect { var center: CGPoint { return CGPoint( x: self.size.width/2.0,y: self.size.height/2.0) } } extension CGPoint { func vector(to p1:CGPoint) -> CGVector { return CGVector(dx: p1.x - x, dy: p1.y - y) } } extension UIBezierPath { func moveCenter(to:CGPoint) -> Self { let bounds = self.cgPath.boundingBox let center = bounds.center let zeroedTo = CGPoint(x: to.x - bounds.origin.x, y: to.y - bounds.origin.y) let vector = center....

May 14, 2019 · 2 min · 223 words · Khoa

How to use CAReplicatorLayer to make activity indicator in iOS

Issue #230 CAReplicatorLayer is a layer that creates a specified number of sublayer copies with varying geometric, temporal, and color transformations Here we use instanceTransform which applies transformation matrix around the center of the replicator layer Below is how we use replicatorLayer to replicate lots of line and rotate them around the center. let replicatorLayer = CAReplicatorLayer() let animation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity)) let line = CALayer() let lineCount: Int = 12 let duration: TimeInterval = 1....

May 13, 2019 · 1 min · 199 words · Khoa

How to do rotation for CALayer in iOS

Issue #229 Use keypath let animation = CASpringAnimation(keyPath: #keyPath(CALayer.transform)) animation.fromValue = 0 animation.valueFunction = CAValueFunction(name: CAValueFunctionName.rotateZ) animation.timingFunction = CAMediaTimingFunction(name: .easeIn) animation.toValue = CGFloat.pi / 4 Avoid setting frame many times Otherwise, frame is the box that covers the rotation transform, and backgroundColor now fills that huge box override func layoutSubviews() { super.layoutSubviews() guard line.frame.width <= 0 else { return } line.backgroundColor = UIColor.red.cgColor line.cornerRadius = 3 line.frame.size = CGSize(width: bounds.width*0.6, height: 6) line....

May 13, 2019 · 1 min · 86 words · Khoa

How to not use isRemovedOnCompletion for CAAnimation in iOS

Issue #228 CAAnimation is about presentation layer, after animation completes, the view snaps back to its original state. If we want to keep the state after animation, then the wrong way is to use CAMediaTimingFillMode.forward and isRemovedOnCompletion Animation never ends forwards https://developer.apple.com/documentation/quartzcore/camediatimingfillmode/1427658-forwards The receiver remains visible in its final state when the animation is completed. isRemovedOnCompletion https://developer.apple.com/documentation/quartzcore/caanimation/1412458-isremovedoncompletion When true, the animation is removed from the target layer’s animations once its active duration has passed....

May 13, 2019 · 1 min · 145 words · Khoa

How to make simple search box in iOS

Issue #227 final class SearchBox: UIView { lazy var textField: UITextField = { let textField = UITextField() let imageView = UIImageView(image: R.image.search()!) imageView.frame.size = CGSize(width: 20 + 8, height: 20) imageView.contentMode = .scaleAspectFit textField.leftView = imageView textField.leftViewMode = .always return textField }() lazy var filterButton: UIButton = { let button = UIButton(type: .custom) button.setImage(R.image.filter()!, for: .normal) button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) return button }() lazy var backView: UIView = { let view = UIView() view....

May 7, 2019 · 1 min · 207 words · Khoa

How to capture video in iOS simulator

Issue #226 Take screenshot xcrun simctl io booted screenshot image.png Record video xcrun simctl io booted recordVideo video.mp4

May 7, 2019 · 1 min · 18 words · Khoa

How to use custom fonts in iOS

Issue #225 <key>UIAppFonts</key> <array> <string>OpenSans-Bold.ttf</string> <string>OpenSans-BoldItalic.ttf</string> <string>OpenSans-ExtraBold.ttf</string> <string>OpenSans-ExtraBoldItalic.ttf</string> <string>OpenSans-Italic.ttf</string> <string>OpenSans-Light.ttf</string> <string>OpenSans-LightItalic.ttf</string> <string>OpenSans-Regular.ttf</string> <string>OpenSans-SemiBold.ttf</string> <string>OpenSans-SemiBoldItalic.ttf</string> </array> Read Adding a Custom Font to Your App The name of the font isn’t always obvious, and rarely matches the font file name. A quick way to find the font name is to get the list of fonts available to your app, which you can do with the following code: for family in UIFont.familyNames.sorted() { let names = UIFont....

May 7, 2019 · 1 min · 81 words · Khoa

How to create UITabBarController programmatically in iOS

Issue #224 let tabBarController = UITabBarController() let navigationController1 = UINavigationController(rootViewController: viewController1) let navigationController2 = UINavigationController(rootViewController: viewController2) let navigationController3 = UINavigationController(rootViewController: viewController3) navigationController2.isNavigationBarHidden = true navigationController1.tabBarItem.image = R.image.profile() navigationController2.tabBarItem.image = R.image.books() navigationController3.tabBarItem.image = R.image.settings() tabBarController.tabBar.tintColor = .yellow tabBarController.viewControllers = [navigationController1, navigationController2, navigationController3] Use tintColor instead of the deprecated selectedImageTintColor to indicate selected item color. For icon size, check Tab Bar Icon Size, usually 50x50 for 2x and 75x75 for 3x In portrait orientation, tab bar icons appear above tab titles....

May 7, 2019 · 1 min · 115 words · Khoa

How to run AppleScript in macOS

Issue #223 Surround script by single quotes let script = """ tell application "XcodeWay" activate end tell """ let command = "osascript -e '\(script)'" let process = Process() process.launchPath = "/bin/bash" process.arguments = ["-c", command] Run as administrator In terminal, we can cd ~/Library sudo mkdir MyNewFolder In code, we use with administrator privileges, this when run will ask for password or fingerprint do shell script "mkdir MyNewFolder" with administrator privileges

May 2, 2019 · 1 min · 71 words · Khoa

How to make simple networking client in Swift

Issue #222 For more mature networking, visit https://github.com/onmyway133/Miami final class NetworkClient { let session: URLSession let baseUrl: URL init(session: URLSession = .shared, baseUrl: URL) { self.session = session self.baseUrl = baseUrl } func make(options: Options, completion: @escaping (Result<Data, Error>) -> Void) { guard let request = options.toRequest(baseUrl: baseUrl) else { completion(.failure(AppError.request)) return } let task = session.dataTask(with: request, completionHandler: { data, _, error in if let data = data { completion(....

May 2, 2019 · 2 min · 290 words · Khoa

How to ignore App Transport Security in iOS

Issue #221 Ignore a host <key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>example.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true/> <key>NSExceptionRequiresForwardSecrecy</key> <true/> <key>NSExceptionMinimumTLSVersion</key> <string>TLSv1.2</string> <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key> <false/> <key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <true/> <key>NSThirdPartyExceptionMinimumTLSVersion</key> <string>TLSv1.2</string> <key>NSRequiresCertificateTransparency</key> <false/> </dict> </dict> </dict> Ignore all <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>

April 30, 2019 · 1 min · 37 words · Khoa

How to run simple http server in Go

Issue #220 Handle url parameter package main import ( "net/http" "log" ) func handleGreeting(w http.ResponseWriter, r *http.Request) { messages, ok := r.URL.Query()["message"] if !ok || len(messages[0]) < 1 { log.Println("Message is missing") w.WriteHeader(400) return } message := messages[0] w.Write([]byte(message)) } func main() { http.HandleFunc("/greet", handleGreeting) if err := http.ListenAndServe(":8080", nil); err != nil { panic(err) } } Handle body type MyRequest struct { Message string `json:"message"` } decoder := json.NewDecoder(r.Body) var t EphemeralKeysRequest err := decoder....

April 30, 2019 · 1 min · 86 words · Khoa

How to use Stripe and Apple Pay in iOS

Issue #219 iOS Integration Setting Up Apple Pay Requirements Apple Pay Show basic add card in iOS import UIKit import Stripe final class MainController: UIViewController { func showPayment() { let addCardViewController = STPAddCardViewController() addCardViewController.delegate = self let navigationController = UINavigationController(rootViewController: addCardViewController) present(navigationController, animated: true, completion: nil) } } extension MainController: STPAddCardViewControllerDelegate { func addCardViewControllerDidCancel(_ addCardViewController: STPAddCardViewController) { dismiss(animated: true, completion: nil) } func addCardViewController(_ addCardViewController: STPAddCardViewController, didCreateToken token: STPToken, completion: @escaping STPErrorBlock) { _ = token....

April 30, 2019 · 9 min · 1870 words · Khoa

How to test PublishSubject in RxSwift

Issue #218 RxBlocking does not work with Variable and PublishSubject, see https://github.com/ReactiveX/RxSwift/blob/0b66f666ba6955a51cba1ad530311b030fa4db9c/Tests/RxSwiftTests/Observable%2BSubscriptionTest.swift#L165 Use homemade Recorder class Recorder<T> { var items = [T]() let bag = DisposeBag() func on(arraySubject: PublishSubject<[T]>) { arraySubject.subscribe(onNext: { value in self.items = value }).disposed(by: bag) } func on(valueSubject: PublishSubject<T>) { valueSubject.subscribe(onNext: { value in self.items.append(value) }).disposed(by: bag) } } Then test final class BookViewModelTests: XCTestCase { func testBooks() throws { let expectation = self.expectation(description: #function) let recorder = Recorder<Book>() let viewModel = BookViewModel(bookClient: MockBookClient()) recorder....

April 29, 2019 · 1 min · 159 words · Khoa

How to fix not found zlib problem in macOS Mojave

Issue #217 https://developer.apple.com/documentation/xcode_release_notes/xcode_10_release_notes The command line tools will search the SDK for system headers by default. However, some software may fail to build correctly against the SDK and require macOS headers to be installed in the base system under /usr/include. If you are the maintainer of such software, we encourage you to update your project to work with the SDK or file a bug report for issues that are preventing you from doing so....

April 29, 2019 · 1 min · 136 words · Khoa