How to get running window informations in macOS

Issue #243 From https://developer.apple.com/documentation/coregraphics/1455137-cgwindowlistcopywindowinfo Generates and returns information about the selected windows in the current user session. struct MyWindowInfo { let frame: CGRect let name: String let pid: Int let number: Int init?(json: [String: Any]) { guard let pid = json["kCGWindowOwnerPID"] as? Int else { return nil } guard let name = json["kCGWindowOwnerName"] as? String else { return nil } guard let rect = json["kCGWindowBounds"] as? [String: Any] else { return nil } guard let x = rect["X"] as?...

May 16, 2019 · 1 min · 174 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 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 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 use Sonarqube in Swift projects

Issue #216 Install Sonarqube https://docs.sonarqube.org/latest/setup/get-started-2-minutes/ Download Sonarqube for macOS https://www.sonarqube.org/downloads/ Put it in ~/sonarqube Run localhost server ~/sonarqube/bin/macosx-universal-64/sonar.sh console Login http://localhost:9000 with admin/admin Create new project Install Sonar scanner https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner Download for macOS 64 bit Put it in ~/sonarscanner export PATH=$PATH:/Users/khoa/sonarscanner/bin Go to project, create sonar-project.properties # must be unique in a given SonarQube instance sonar.projectKey=my-app # this is the name and version displayed in the SonarQube UI. Was mandatory prior to SonarQube 6....

April 29, 2019 · 3 min · 554 words · Khoa

How to map from Swift 5 Resul to RxSwift PublishSubject

Issue #214 extension Result { func to(subject: PublishSubject<Success>) { switch self { case .success(let value): subject.onNext(value) case .failure(let error): subject.onError(error) } } }

April 26, 2019 · 1 min · 23 words · Khoa

How to use Timer in Swift

Issue #212 Pre iOS 10 func schedule() { DispatchQueue.main.async { self.timer = Timer.scheduledTimer(timeInterval: 20, target: self, selector: #selector(self.timerDidFire(timer:)), userInfo: nil, repeats: false) } } @objc private func timerDidFire(timer: Timer) { print(timer) } iOS 10+ DispatchQueue.main.async { self.timer = Timer.scheduledTimer(withTimeInterval: 20, repeats: false) { timer in print(timer) } } Note that It needs to be on the main queue Callback function can be public, private, … Callback function needs to be @objc Original answer https://stackoverflow....

April 23, 2019 · 1 min · 74 words · Khoa

How to overload functions in Swift

Issue #211 Function Functions in Swift are distinguishable by parameter label parameter type return type so that these are all valid, and works for subscript as well struct A { // return type func get() -> String { return "" } func get() -> Int { return 1 } // mix of parameter type and return type func get(param: String) -> String { return "" } func get(param: String) -> Int { return 1 } func get(param: Int) -> Int { return 1 } func get(param: Int) -> String { return "" } subscript(param: String) -> String { return "" } subscript(param: String) -> Int { return 1 } subscript(param: Int) -> Int { return 1 } subscript(param: Int) -> String { return "" } // parameter label func set(int: Int) {} func set(string: String) {} // concrete type from generic func get(param: Array<String>) -> String { return "" } func get(param: Array<Int>) -> Int { return 1 } subscript(param: Array<String>) -> String { return "" } subscript(param: Array<Int>) -> Int { return 1 } } When you specialize a generic type, like Array<Int>, you’re actually using a concrete type...

April 18, 2019 · 2 min · 261 words · Khoa

How to check file under Library in macOS

Issue #200 let home = NSSearchPathForDirectoriesInDomains(.applicationScriptsDirectory, .userDomainMask, true).first! let path = home.appending(".XcodeWayExtensions/XcodeWayScript.scpt") let exists = FileManager.default.fileExists(atPath: path)

April 10, 2019 · 1 min · 17 words · Khoa

How to generate grpc protobuf files

Issue #197 protoc https://grpc.io/docs/quickstart/go.html Install the protoc compiler that is used to generate gRPC service code. The simplest way to do this is to download pre-compiled binaries for your platform(protoc--.zip) from here: https://github.com/google/protobuf/releases Unzip this file. Update the environment variable PATH to include the path to the protoc binary file. Go protoc plugin https://github.com/golang/protobuf go get -u github.com/golang/protobuf/protoc-gen-go export PATH=$PATH:$GOPATH/bin source ~/.zshrc Swift protoc plugin https://github.com/grpc/grpc-swift The recommended way to use Swift gRPC is to first define an API using the Protocol Buffer language and then use the Protocol Buffer Compiler and the Swift Protobuf and Swift gRPC plugins to generate the necessary support code....

April 8, 2019 · 2 min · 252 words · Khoa

How to build a networking in Swift

Issue #195 Miami https://github.com/onmyway133/Miami Future based builders Should not wrap system API URLSession offer tons of thing that it’s hard to use with wrappers like Alamofire Concerns Parameter encoding is confusing -https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#parameter-encoding Query and body builder Understanding HTML Form Encoding: URL Encoded and Multipart Forms https://stackoverflow.com/questions/14551194/how-are-parameters-sent-in-an-http-post-request https://stackoverflow.com/questions/1617058/ok-to-skip-slash-before-query-string https://stackoverflow.com/questions/3508338/what-is-the-boundary-in-multipart-form-data How to construct URL with URLComponents and appendPathComponent in Swift HTTP Case sensitivity in HTTP Lazy execution Promise https://github.com/onmyway133/Then Signal and Future https://github....

April 5, 2019 · 6 min · 1156 words · Khoa