Post

Replies

Boosts

Views

Activity

Why does 'defer { do { ...' jump the queue?
In real life code, I want to have a defer issued "up top" of a method, but in one edge case I'd like to have another defer that runs before the original one (now thinking about this I may be able to solve it in a traditional sense).I saw something online that suggested using 'defer { defer { <code> } }' In fact that does work, but generates a warning in Xcode 11b4-beta, with a fix suggestion of using 'defer { do { <code> } }'. That actually works - but I don't understand why!var goo = 0 while goo < 10 { defer { print("LAST", goo) } defer { defer { print("(Want First)", goo) } } // want it to execute before the LAST print but clang warning defer { do { print("First") } } // what the compiler tells me to do goo += 1 }Console output:First (Want First) 1 LAST 1So the double defer does do what I want, which I understand, and the 'defer-do' also works, but I'd l;ove to know why it works!
3
0
962
Feb ’20
Linker flag to disable "building for iOS Simulator [but object] built for macOS"
I'm using an open source library (libturbojpeg), and the library has been built more or less the same for years. The 2.0.2 version links fine for Device and Simulator in both Xcode 11.3 and 11.4.1-beta.But newer releases generate warnings in 11.3 when using 2.0.3 or newer (for example):ld: warning: building for iOS Simulator, but linking in object file (/Volumes/Data/git/PhotoScrollerSwiftPackage/Libraries/libturbojpeg.a(jdapimin.c.o)) built for macOSWorse yet, in Xcode 11.4.1-beta, those turn into hard errors and the build fails:error: Building for iOS Simulator, but the linked library '208libturbojpeg.a' was built for macOS + iOS. (in target 'LTJTest' from project 'LTJTest')This issue first showed up here (as best I can tell) in this thread.Since these really only affect the Simulator builds, is there anyway to disable them?
2
0
5.9k
Feb ’20
NWPathMonitor fails to report WIFI coming back if cellular is on
Feedback FB7556677This is my code:private lazy var pmC = NWPathMonitor(requiredInterfaceType: .cellular) private lazy var pmW = NWPathMonitor(requiredInterfaceType: .wifi) pmC.pathUpdateHandler = { (path: NWPath) in print("C PATH STATUS:", path.status) path.availableInterfaces.forEach( { interfce in DispatchQueue.main.async { print(" C INTERFACE:", interfce, "Status:", path.status) } } ) } pmC.start(queue: assetQueue) pmW.pathUpdateHandler = { (path: NWPath) in print("W PATH STATUS:", path.status) path.availableInterfaces.forEach( { interfce in DispatchQueue.main.async { print(" W INTERFACE:", interfce, "Status:", path.status) } } ) } pmW.start(queue: assetQueue)Do a test. Lauch with both cellular and wifi on. Works as expected. Turn WIFI off, works again. Turn WIFI back on - nothing. So as far as I know, I've only got an "expensive network" available, even though WIFI is on and I can use it in Safari.Console Log:// WIFI and CELLULAR ON, launch C PATH STATUS: satisfied W PATH STATUS: satisfied C INTERFACE: pdp_ip0 Status: satisfied W INTERFACE: en0 Status: satisfied // Turn Cell off C PATH STATUS: unsatisfied // Turn WIFI off W PATH STATUS: unsatisfied // Turn Cell on C PATH STATUS: satisfied C INTERFACE: pdp_ip0 Status: satisfied C PATH STATUS: satisfied C INTERFACE: pdp_ip0 Status: satisfied C PATH STATUS: satisfied C INTERFACE: pdp_ip0 Status: satisfied // WIFI on ... nothingEven switched to Safari, opened a web page, then switched back. Nothing after many minutes.Note: iOS 13.3 iPhone 6s+ I tried and tried to get a sysdiagnose - volume buttons and power button for 1+ seconds, nothing happens.
1
0
1.1k
Jan ’20
How to use NWPathMonitor to assess overall network state?
I can create an instance of NWPathMonitor to monitor a single type of interface (WIFI, cellular, etc) via a labeled init, or I can monitor the overall system (all interfaces) using "init()".Great! That's what I want to know - is there any interface to the internet that's "satisfiled". The only way to get status is listen for updates by providing a block, that provides a NWPath object. At least one documentation page says that object is hashable (but the Swift interface in Xcode for iOS13 does not say that).What I **beiieve** i need to do is save all path status' in a dictionary, and when I my block runs, save the state for that particular path (might be cellular, or wifi, or wired, whatever). Then at some point when I need status, I see if any interface is "satisfied" and if not no network.But I can't save the path in the dictionary - its not hashable! I thought - well, I could use the "debugDescription" as a unique value - shutter shutter!I have to believe I have misunderstood usage, but I don't find this concept covered in any of relevant blog posts.
1
0
2k
Jan ’20
Why does unwrapping an optional func change its signature?
I'm writing a InputStream (aka NSInputStream) subclass, which has an optional delegate that has one optional function:public protocol StreamDelegate : NSObjectProtocol { optional func stream(_ aStream: Stream, handle eventCode: Stream.Event) }When I use the delegate directly, I use the "proper" form of the function, which has a second named label of "handle". But when I unwrap the function, the signature appears to have changed, and Xcode tells me I need to remove the label. [Note: did not try running this code at all.]guard let delegate = inputStream.delegate, let stream = delegate.stream else { return } delegate.stream?(fetcher, handle: .openCompleted) // OK stream(fetcher, handle: .openCompleted) // error: extraneous argument label 'handle:' in callWhat's the reason for this (and/or is the compiler wrong)?
5
0
1.3k
Jan ’20
Stepper: how to make label font as large as possible?
Imagine a Stepper with a left label (from troz.net):Stepper(value: $stepperValue, in: 0...20) { Text("Value in child = \(stepperValue)") .font(.headline) .fontWeight(.medium) .multilineTextAlignment(.leading) //.minimumScaleFactor(0.50) }The label could change or be a different language. What I tried (unsuccessfully) to do in the last line is have the label fit as large a rect as the Stepper could allow. but when I uncomment the minimumScaleFactor line, the text shrinks immediately to that size.How can I get the labe lto scale so the full horizonal space (with readable padding) is consumed?
2
0
1.4k
Jan ’20
@autoclosure causes Segmentation Fault
Experimenting with @autoclosure with variatic parameters. With that qualifier there, compiler faults. Comment just "@autoclosure" out, then it compiles just fine. Code:fileprivate func LOG(_ flag: Int, _ items: @autoclosure Any..., separator: String = " ", terminator: String = "\n") { if flag > 0 { // Commenting these out has no effect let str = items.map{String(describing: $0)}.joined(separator: separator) print(str, terminator: terminator) } } class ViewController: UIViewController { var notificationTimer = DispatchWorkItem(block: {} ) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. LOG(1, "Does it get called?", 5, 7, expensiveFunc()) // Segmentation fault //LOG(0, "Does it get called?", expensiveFunc()) // OK } func expensiveFunc() -> String { print("CALLED") return "EXPENSIVE!!!" } }Fault:<unknown>:0: error: unable to execute command: Segmentation fault: 11<unknown>:0: error: compile command failed due to signal 11 (use -v to see invocation)Xcode 11.2, Mac -> latest Catalina, Target iPhone 13.2Where should I enter the bug report? Also, is there a workaround for this?
2
0
654
Dec ’19
AVPlayerLooper fails when there is a AVVideoComposition
I have a 30 second video I want to loop and uses an AVVideoComposition. It works flawlessly in the Catalina Simulator, but fails on my iPad 9.7". Originally I thought the problem was with the CIFilters, but in the end it was the simple existence of the composition block:func runMovie() { playerItem = AVPlayerItem(asset: asset) let videoComposition = AVVideoComposition(asset: asset, applyingCIFiltersWithHandler: { request in let outputImage = request.sourceImage request.finish(with: outputImage, context: nil) }) playerItem.videoComposition = videoComposition let duration = CMTime(seconds: 30.0, preferredTimescale: CMTimeScale(1)) let plyr = AVQueuePlayer() let timeRange = CMTimeRange(start: CMTime.zero, duration: duration) playerLooper = AVPlayerLooper(player: plyr, templateItem: playerItem, timeRange: timeRange) playerLayer = AVPlayerLayer(player: player) playerLayer.frame = view.bounds //bounds of the view in which AVPlayer should be displayed playerLayer.videoGravity = .resizeAspect view.layer.addSublayer(playerLayer) plyr.play() print("PLAY VIDEO", player.status.rawValue) startDate = Date() let _ = timer// starts 1 second timer }The player runs one or more loops, then the video stops. I have a timer running checking the AVLooper status, and this is the error I see://if playerLooper.status == .failed { // print("ERROR:", playerLooper.error ?? "No Error") // ERROR: Error Domain=AVFoundationErrorDomain Code=-11819 "Cannot Complete Action" UserInfo={NSLocalizedDescription=Cannot Complete Action, NSLocalizedRecoverySuggestion=Try again later.} Leave the video composition out, it loops forever, add the compostion, it fails in a min or two.PS: this is a HEVC video I created from a standard mov per the 2019 WWDC 506 Session:guard let export = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHEVCHighestQualityWithAlpha) else { fatalError() } let scale = CMTimeScale(1) export.timeRange = CMTimeRange(start: CMTime.zero, duration: CMTime(seconds: 31.0, preferredTimescale: scale)) export.outputFileType = AVFileType.mov //let url = URL(fileURLWithPath: "/tmp/Original-transparent.mov") let url = URL(fileURLWithPath: "/tmp/Original-transparent.mov") try? FileManager.default.removeItem(at: url) export.outputURL = url export.videoComposition = videoComposition export.exportAsynchronously(completionHandler: { DispatchQueue.main.async { NSLog("...VIDEO DONE") self.makingVideoNow = false } }) NSLog("START VIDEO...")
2
0
1.4k
Dec ’19
Stuck on CGDataProviderCreateWithData
What I'd like to do is provide a CVPixelBuffer as the dataInfo argument to CGDataProviderCreateWithData that has an initializer:init?(dataInfo info: UnsafeMutableRawPointer?, data: UnsafeRawPointer, size: Int, releaseData: @escaping CGDataProviderReleaseDataCallback)My best (and probably wrong) approach to convert to a UnsafeRawPointer is:let pixelBuffer: CVPixelBuffer ... let ptr: UnsafeMutableRawPointer = UnsafeMutableRawPointer(mutating: &pixelBuffer)However, the releaseData callback function is defined as:typealias CGDataProviderReleaseDataCallback = (UnsafeMutableRawPointer?, UnsafeRawPointer, Int) -> VoidI cannot think of any way to get the CVPixelBuffer back from the UnsafeMutableRawPointer. Clearly I need help!
7
0
3.5k
Jun ’17
WeakSelf/StrongSelf dance: __strong needed?
I read today in the Swift book:__weak typeof(self) weakSelf = self; self.block = ^{ __strong typeof(self) strongSelf = weakSelf; [strongSelf doSomething]; } // Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C (Swift 3.1).”When I saw '__strong' I got a bit concerned - in the past I had always used "typeof(self) strongSelf = weakSelf;, think the typeof made strongSelf strong.Yikes! Did I get it wrong all these years???
2
0
2.9k
Apr ’17
"private lazy var ..." thread safe?
Just had a weird crash in development in Simulator - first of a kind. The crash was on this line:private lazy var regExTrimSet = NSCharacterSet(charactersInString: " \t\r\n_")and the error was some malloc() already released (grrr, should have copied it). Should that be thread safe? [Its being referenced by a bunch of concurrent blocks at one point]Also, I tried to find out where the Xcode console log might get written, but had no luck finding a link. Is there one that this error should be logged to?
6
0
4.6k
Oct ’15