Xcode tips

Issue #584 Read more https://dasdom.github.io/a-breakpoint-i-cannot-live-without/

January 26, 2020 · 1 min · 5 words · Khoa

How to test drag and drop in UITests

Issue #583 In UITests, we can use press from XCUIElement to test drag and drop let fromCat = app.buttons["cat1"].firstMatch let toCat = app.buttons["cat2"] let fromCoordinate = fromCat.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0)) let toCoordinate = toCat.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: -0.5)) fromCoordinate.press(forDuration: 1, thenDragTo: toCoordinate) and then take screenshot let screenshot = XCUIScreen.main.screenshot() let attachment = XCTAttachment(screenshot: screenshot) attachment.lifetime = .keepAlways attachment.name = name add(attachment) Screenshot capturing happens after the action, so it may be too late....

January 23, 2020 · 1 min · 167 words · Khoa

How to set corner radius in iOS

Issue #582 Use View Debugging Run on device, Xcode -> Debug -> View debugging -> Rendering -> Color blended layer On Simulator -> Debug -> Color Blended Layer Corner radius https://twitter.com/timoliverau/status/1135999854176395264 Okay. Talked to a Core Animation engineer again: cornerRadius was deliberately improved in Metal so it could be used everywhere. Using a bitmap is WAY heavier in terms of memory and performance. CALayer maskLayer is still heavy. https://developer.apple.com/documentation/quartzcore/calayer/1410818-cornerradius Setting the radius to a value greater than 0....

January 22, 2020 · 4 min · 790 words · Khoa

How to deal with Swift slow compile time

Issue #581 Read more https://engineering.circle.com/swift-compiler-performance-tips-and-tricks-e86a53a5b42a https://swiftrocks.com/reducing-ios-build-times-by-using-interface-targets.html

January 21, 2020 · 1 min · 6 words · Khoa

How to work with SceneDelegate in iOS 12

Issue #580 Events open url https://stackoverflow.com/questions/58624786/method-applicationopenurloptions-is-not-called Implement scene(_:openURLContexts:) in your scene delegate. If the URL launches your app, you will get scene(_:willConnectTo:options:) instead and it’s in the options. life cycle https://stackoverflow.com/questions/56508764/app-delegate-methods-arent-being-called-in-ios-13 Here’s how it works: If you have an “Application Scene Manifest” in your Info.plist and your app delegate has a configurationForConnectingSceneSession method, the UIApplication won’t send background and foreground lifecycle messages to your app delegate. That means the code in these methods won’t run:...

January 20, 2020 · 2 min · 300 words · Khoa

How to handle radio group for NSButton

Issue #579 Use same action, or we can roll our own implementation An NSButton configured as a radio button (with the -buttonType set to NSRadioButton), will now operate in a radio button group for applications linked on 10.8 and later. To have the button work in a radio group, use the same -action for each NSButton instance, and have the same superview for each button. When these conditions are met, checking one button (by changing the -state to 1), will uncheck all other buttons (by setting their -state to 0)....

January 17, 2020 · 1 min · 111 words · Khoa

How to specify locale in Swift

Issue #578 Locale Read Language and Locale IDs zh-Hans_HK [language designator]-[script designator]_[region designator] Language IDs A language ID identifies a language used in many regions, a dialect used in a specific region, or a script used in multiple regions. To specify a language used in many regions, use a language designator by itself. To specify a specific dialect, use a hyphen to combine a language designator with a region designator. To specify a script, combine a language designator with a script designator....

January 14, 2020 · 2 min · 364 words · Khoa

How to workaround URLSession issue in watchOS 6.1.1

Issue #577 https://stackoverflow.com/questions/59724731/class-avassetdownloadtask-is-implemented-in-both-cfnetwork-and-avfoundation objc[45250]: Class AVAssetDownloadTask is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CFNetwork.framework/CFNetwork (0x4ddd0ec) and /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/AVFoundation.framework/AVFoundation (0x16aea494). One of the two will be used. Which one is undefined. objc[45250]: Class AVAssetDownloadURLSession is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CFNetwork.framework/CFNetwork (0x4dddd44) and /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/AVFoundation.framework/AVFoundation (0x16aea4bc). One of the two will be used. Which one is undefined. Then URLSession stops working. 2020-01-13 22:50:12.430920+0100 MyAppWatch WatchKit Extension[45250:2099229] Task <3CECDE81-59B9-4EDE-A4ED-1BA173646037>.<1> finished with error [-999] Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=https://myapp.com/def.json, NSErrorFailingURLStringKey=https://myapp.com/def.json, NSLocalizedDescription=cancelled} The workaround is to remove Combine based API, and use completion block....

January 13, 2020 · 1 min · 165 words · Khoa

How to generate XCTest test methods

Issue #576 Code See Spek Override testInvocations to specify test methods https://developer.apple.com/documentation/xctest/xctestcase/1496271-testinvocations Returns an array of invocations representing each test method in the test case. Because testInvocations is unavailable in Swift, we need to use ObjC #import "include/SpekHelperTestCase.h" @implementation SpekHelperTestCase - (instancetype)init { self = [super initWithInvocation: nil]; return self; } + (NSArray<NSInvocation *> *)testInvocations { NSArray<NSString *> *selectorStrings = [self spekGenerateTestMethodNames]; NSMutableArray<NSInvocation *> *invocations = [NSMutableArray arrayWithCapacity:selectorStrings.count]; for (NSString *selectorString in selectorStrings) { SEL selector = NSSelectorFromString(selectorString); NSMethodSignature *signature = [self instanceMethodSignatureForSelector:selector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; invocation....

January 12, 2020 · 2 min · 215 words · Khoa

How to use ObjC in Swift Package Manager

Issue #575 Create Objc target http://ankit.im/swift/2016/05/21/creating-objc-cpp-packages-with-swift-package-manager/ Check runtime Check for example _runtime(_ObjC) or os(macOS if you plan to use platform specific feature https://github.com/Quick/Quick/blob/master/Package.swift https://github.com/Quick/Quick/pull/687/files For example, in test we use XCTest which is run via Xcode and is a macOS framework, so we need to check for os(macOS) Note that in Objc framework, the header files must be in include folder targets: { var targets: [Target] = [ .testTarget( name: "QuickTests", dependencies: [ "Quick", "Nimble" ], exclude: [ "QuickAfterSuiteTests/AfterSuiteTests+ObjC....

January 11, 2020 · 1 min · 115 words · Khoa

How to expression cast type in lldb in Swit

Issue #574 expr -l Swift -- import UIKit expr -l Swift -- let $collectionView = unsafeBitCast(0x7fddd8180000, to: UICollectionView.self) expr -l Swift -- $collectionView.safeAreaInsets

January 10, 2020 · 1 min · 23 words · Khoa

How to use Applications folder in macOS

Issue #573 There are 2 Applications folder /System/Applications: contains Notes, Books, Calculator, … /Applications: contains Safari, Xcode, Keynote, …

January 8, 2020 · 1 min · 19 words · Khoa

How to fix library not found with SPM and CocoaPods in Xcode

Issue #572 After migrating a few pods to use SPM, some libraries fail to load. This is because the workspace now uses both SPM and cocoapods code signature in … not valid for use in process using Library Validation: mapped file has no Team ID and is not a platform binary (signed with custom identity or adhoc?) The workaround is to disable Library validation

January 8, 2020 · 1 min · 64 words · Khoa

How to make rotation in same direction in iOS

Issue #571 From CGFloat.pi / 2 to -CGFloat.pi / 2 + epsilon

January 6, 2020 · 1 min · 12 words · Khoa

How to get updated safeAreaInsets in iOS

Issue #570 Use viewSafeArea @available(iOS 11.0, *) override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() self.collectionView.reloadData() } Use https://developer.apple.com/documentation/uikit/uiview/2891102-safearealayoutguide view.safeAreaLayoutGuide.layoutFrame https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets For the view controller’s root view, the insets account for the status bar, other visible bars, and any additional insets that you specified using the additionalSafeAreaInsets property of your view controller. For other views in the view hierarchy, the insets reflect only the portion of the view that is covered. For example, if a view is entirely within the safe area of its superview, the edge insets in this property are 0....

January 6, 2020 · 2 min · 333 words · Khoa

How to disable implicit decoration view animation in UICollectionView

Issue #569 From documentation https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617726-initiallayoutattributesforappear This method is called after the prepare(forCollectionViewUpdates:) method and before the finalizeCollectionViewUpdates() method for any decoration views that are about to be inserted. Your implementation should return the layout information that describes the initial position and state of the view. The collection view uses this information as the starting point for any animations. (The end point of the animation is the view’s new location in the collection view....

January 6, 2020 · 1 min · 179 words · Khoa

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 · 158 words · Khoa

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 · 963 words · Khoa

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 · 682 words · Khoa

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 · 13 words · Khoa