Post not yet marked as solved
I tried running the following code and it raises the following error every time:
DispatchQueue.main.sync { }
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
I found this post on stackoverflow that says to never run synchronous code on the main queue:
DispatchQueue crashing with main.sync in Swift
I had assumed that because the sync { } method is there that means there is some context that it can be used. Is there absolutely no use for executing synchronous code on the main queue?
Post not yet marked as solved
I have code that I inherited - and there is very liberal use of DispatchQueue.main.async because they were concerned the UI code there wasn't on the main thread - but it already was on the main queue.
The bug I saw, was that if the calling code was already on the main thread, and the function they called also called the DispatchQueue.main.async, it seems like that call was delayed/not-called, and being requeued on the run loop for the next call.
Here's kind of a general - very stripped down - version of what I was experiencing:
var result = 1
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.async {
print("Before : result = \(self.result)")
self.doStuff()
print("After : result = \(self.result)")
}
}
func doStuff() {
self.result += 1
self.doStuff2()
}
func doStuff2() {
DispatchQueue.main.async {
self.result += 1
self.doStuff3()
}
}
func doStuff3() {
result += 1
}
}
The output is:
Before : result = 1
After : result = 2
So it enters doStuff2() but that function also calls DispatchQueue.main.async - and therefore, that code never gets executed.
I cleaned it up by removing these extraneous calls - but it took A LONG TIME tracking all of them down.
Is there any better way to debug this?
Also - they said this code worked in iOS 12.
Thanks,
Scott
Post not yet marked as solved
I am implementing asset pipelines for a metal app and am deciding between the new Metal IO support and more traditional approaches like dispatch_io. Does the MTLCommandQueue use GCD as its backend, or how do the approaches compare?
Post not yet marked as solved
I use as many cpu's as I can get with DispatchQueue. How do I test the Mac for cpu count in my code?
Post not yet marked as solved
I've been trying to use the Xcode 14 beta and the -warn-concurrency flag to make some of our library code concurrency-safe, and I've hit just… too many problems to manage.
A smattering of random data points:
Foundation types that I think should be Sendable, are not:
URL
Notification
...
UIKit constants that should not be @MainActor, are:
UIApplication.willEnterForegroundNotification (it's just a string constant, and NotificationCenter itself is thread-safe)
UIKit types and methods that I think should not be @MainActor, are:
UIDevice, or at least I should be able to do UIDevice.current.systemVersion from any actor
Dispatch is completely concurrency-unaware — I kinda expected it to be unavailable, but instead it's available but doesn't understand swift concurrency
It'd at least be nice if DispatchQueue.main.[a]sync understood that its closure can be @MainActor (perhaps main could return a subclass of DispatchQueue with stronger guarantees?)
SwiftUI Button etc. callbacks aren't marked @MainActor, even though (AFAIK) they are — certainly it's always been legal to update @State vars from them — so it's not legal to call UIKit from them (eg. to present a UIViewController in response to a button press)
When can we expect Apple's SDKs to actually be usable with concurrency checking?
Post not yet marked as solved
Hi folks,
I am downloading some images from Firebase and adding them to main bundle resources, after which I use them.
I am having trouble with making my code to wait for the downloads to get complete before it executes the next statement.
I tried completion handlers, async/await but still the same.
Not sure if I am doing it the right way.
Can anyone help what is the correct approach for this scenario.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARImageTrackingConfiguration()
Task{
await self.checkForDownloads.refreshResources(forUser: self.username)
}
if let trackedImages = ARReferenceImage.referenceImages(inGroupNamed: "AR Resources", bundle: Bundle.main){
configuration.trackingImages = trackedImages
configuration.maximumNumberOfTrackedImages = 1
print("Images Found: \(trackedImages.count)")
}
sceneView.session.run(configuration)
}
func refreshResources(forUser username: String) async {
//..
}
I am expecting checkForDownloads.refreshResources to finish downloading first, then proceed to next statement.
Hi,
So I am using this function getListAtFIRStore() which is fetching data from firestore and returning it. But the fetching takes some time and before that happens the function already returns back the array which is empty at that moment.
How do I wait for the fetching task to be completed before the function returns the array back?
class CheckForDownloads {
var userName = String()
func refreshResources(forUser username: String) {
self.userName = username
let listOfImagesAtFirestore = getListAtFIRStore()
print(listOfImagesAtFirestore)
}
func getListAtFIRStore() -> [String]{
let root = Storage.storage().reference()
var str3 = [String]()
root.child("MagicFrame/\(userName)/images").listAll { (result, error) in
if let error = error {
print("Error in fetching list from firestore \(error.localizedDescription)")
}else{
for item in result.items{
if let str1 = (item.description.components(separatedBy: ["/"]).last) {
if let str2 = (str1.components(separatedBy: ["."])).first{
print(str2)
str3.append(str2)
}
}
}
}
}
return str3
}
}
Post not yet marked as solved
Hi, i'm quite new to iOS Development and i'm looking for some useful informations for my project.
The phone connects to a device via BLE and receives data from it at an high rate ( 4x hundreds data points per seconds) [--> Thread 1 ]
and this data need to be analyzed in real time [--> Thread 2].
The app has to work for between 1 to 8 hours and all of this needs to work both when the phone is in the foreground and when is in the background (Background Task).
Can you help me with any useful tips / information on how to accomplish this?
Thank you
Hi, I'm trying to use time measurement in a test application on Windows. Therefore I use the DispatchTime.now() function like this:
let timeBefore = DispatchTime.now()
While searching online all examples used the function like this. Now I'm getting an error while compiling:
←[1msrc/main.swift:115:26: ←[0m←[0;1;31merror: ←[0m←[1mcannot find 'DispatchTime' in scope
←[0m let timeBefore = DispatchTime.now()
←[0;1;32m ^~~~~~~~~~~~
←[0mNMAKE : fatal error U1077: "swiftc": Rückgabe-Code "0x1"
Is there something missing? Like an import? Or is this an issue with Windows and if that's the case, is there a workaround or other function to use?
Post not yet marked as solved
[Q] Are there any known common reasons/patterns why libdispatch would face unexpected events?
Application Specific Information:
BUG IN LIBDISPATCH: Unexpected event
...
0 _dispatch_mach_reply_merge_evt + 29
1 _dispatch_kq_drain + 166
2 _dispatch_event_loop_drain + 312
3 _dispatch_lane_serial_drain + 803
4 _dispatch_lane_invoke + 366
5 _dispatch_workloop_worker_thread + 811
6 _pthread_wqthread + 314
7 start_wqthread + 15
There’s also a bit of a mystery with this backtrace as the libdispatch source code (from https://opensource.apple.com/releases) does not list _dispatch_mach_reply_merge_evt (or dux_merge_evt) as being called by _dispatch_kq_drain.
Post not yet marked as solved
The Xcode console logs an identifier indicating the current thread that's running when a message is print()ed from Swift. Some more complex logging systems (e.g. swift-log and console-kit) don't provide that information, and I'm trying to write a logging back-end for swift-log that will.
Thing is, I don't see any way to get the current queue name in Swift. I tried
dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)
But I get "cannot convert value of type '()' to expected argument type 'DispatchQueue?'". Passing nil instead results in "'dispatch_queue_get_label' has been replaced by property 'DispatchQueue.label'".
This is not an unreasonable thing to want to do, and it poses no safety concerns.
I have been working with Apple's Network Framework to implement a WebSocket Client. Here is the receive block for my code:
nw_connection_receive(connection, 1, UINT32_MAX, ^(dispatch_data_t content, nw_content_context_t context, bool is_complete, nw_error_t receive_error) {
nw_retain(context);
nw_protocol_metadata_t wsMetadata = nw_content_context_copy_protocol_metadata(context,nw_protocol_copy_ws_definition());
nw_ws_opcode_t inputOpCode = nw_ws_metadata_get_opcode(wsMetadata);
fprintf(stderr,"\n\nInput Opcode: %d\n", inputOpCode);
dispatch_block_t schedule_next_receive = ^{
// If the context is marked as complete, and is the final context,
// we're read-closed.
if (is_complete &&
(context == NULL || nw_content_context_get_is_final(context))) {
exit(0);
}
// If there was no error in receiving, request more data
if (receive_error == NULL) {
receive_loop(connection);
}
nw_release(context);
};
if (content != NULL) {
// If there is content, write it to stdout asynchronously
schedule_next_receive = Block_copy(schedule_next_receive);
dispatch_write(STDOUT_FILENO, content,dispatch_get_main_queue(), ^(__unused dispatch_data_t _Nullable data, int stdout_error) {
if (stdout_error != 0) {
errno = stdout_error;
fprintf(stderr,"stdout write error\n");
} else {
schedule_next_receive();
}
Block_release(schedule_next_receive);
});
} else {
// Content was NULL, so directly schedule the next receive
schedule_next_receive();
}
});
This code block is taken from (Implementing netcat with Network Framework | Apple Developer Documentation).
I now want to get rid of the dispatch_write block and convert the received dispatch_data_t object to a string representation either a CFStringRef or a C++ std::string.
Post not yet marked as solved
I'm new at Swift and that's why i need your help. So I have a function which should send request and return a value
func getAnswer() -> String? {
var answer: String?
guard let url = URL(string: "https://8ball.delegator.com/magic/JSON/_") else { return nil }
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
return
}
guard let response = response as? HTTPURLResponse else { return }
guard response.statusCode == 200 else { return }
do {
let model = try JSONDecoder().decode(Answer.self, from: data)
DispatchQueue.main.async {
answer = model.magic.answer
}
} catch let error {
fatalError(error.localizedDescription)
}
}.resume()
return answer
}
but it always returns nil.
I suppose problem is here
DispatchQueue.main.async {
answer = model.magic.answer
}
How can I resolve it?
I created the playground below to answer my question "If I created a class instance using DispatchQueue.global().async would that class remain in its own asynchronous queue? Even if the main app called one of that classes methods, would that method run asynchronously compared to the main app?
With the sleep line I discovered that the answer is "no."
But I am curious if there is a legit way to do this? Or even if there is, it is considered bad programming?
import UIKit
class MyFunx : NSObject {
var opsCount = 0
override init() {
super.init()
}
func addValues (a: Int, b: Int) {
let c = a + b
opsCount += 1
sleep(1)
}
}
var firstVar = 0
var secondVar = 0
var myFunx : MyFunx?
while secondVar < 100 {
print ("starting")
if myFunx == nil {
print ("making myFunx")
DispatchQueue.global().async {
myFunx = MyFunx()
}
} else {
myFunx!.addValues(a: firstVar, b: secondVar)
}
firstVar += 1
secondVar += 1
}
print ("myFunx = \(myFunx)")
print ("\(myFunx?.opsCount)")
print ("exiting")
In the code snippet below, I am trying to have a routine run concurrently with GCD. However, the queue runs the code serially. How would one force the queue to run concurrently?
The WWDC 2017 VIDEO shows:
dispatch_apply( DISPATCH_APPLY_AUTO , count , ^(size_t i) { ...} );
but Xcode doesn't seem to recognize this syntax. Would there be a value for the flag parameter of dispatch_get_global_queue that would force concurrency.
code-block
dispatch_queue_t aQueue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0);
dispatch_apply( turnsMax , aQueue , ^( size_t t )
{
Post not yet marked as solved
Hi, all:
more details appreciated about why this crash happened.
as you can see, it crashed when socket readcomplete, but why trigger a sigtrap in libdispatch?
crash stack as follow:
Trigger Thread:10
appversion : xxxx
CFBundleShortVersionString : xxxx
CFBundleName : xxxx
packagename : xxxx
boot_time : 2021-12-04T01:08:28Z
kernel_version : Darwin Kernel Version 21.0.0: Sun Aug 15 20:55:49 PDT 2021; root:xnu-8019.12.5~1/RELEASE_ARM64_T8110
process_name : xxxxx
process_id : 1322
parent_process_id : 1
Exception Codes: #0 at 0x00000001820a6f5c
Exception Type: SIGTRAP
ExtraInfo:{FirstLaunch:0,FirstInstall:0,PT:box.medusa.bbammsimagesearchviewcontroller1229,remjsVer = 3.380.2, isPrejs = 1, prejsVer = 3.370.10, }
Code Type: arm64
OS Version: iPhone OS 15.0 (19A344)
Hardware Model: iPhone14,5
Launch Time: 2021-12-06 13:56:33
Date/Time: 2021-12-07 18:59:42
Thread 10 Crashed:
0 libdispatch.dylib __dispatch_event_loop_end_ownership.cold.1 (in libdispatch.dylib) 28
1 libdispatch.dylib __dispatch_lane_barrier_sync_invoke_and_complete (in libdispatch.dylib) 176
2 CoreFoundation ___CFFileDescriptorDisableCallBacks_block_invoke (in CoreFoundation) 372
3 *** base::MessagePumpIOSForIO::FdWatchController::StopWatchingFileDescriptor() (in ***) 196
4 *** net::SocketPosix::ReadCompleted() (in ***) 16
5 *** base::MessagePumpIOSForIO::HandleFdIOEvent(__CFFileDescriptor*, unsigned long, void*) (in ***) 120
6 CoreFoundation ___CFFileDescriptorPerform (in CoreFoundation) 356
7 CoreFoundation ___CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ (in CoreFoundation) 28
8 CoreFoundation ___CFRunLoopDoSource0 (in CoreFoundation) 208
9 CoreFoundation ___CFRunLoopDoSources0 (in CoreFoundation) 376
10 CoreFoundation ___CFRunLoopRun (in CoreFoundation) 820
11 CoreFoundation -[__NSCFString appendString:] (in CoreFoundation) 9040
12 Foundation -[NSRunLoop(NSRunLoop) runMode:beforeDate:] (in Foundation) 236
13 *** base::MessagePumpNSRunLoop::DoRun(base::MessagePump::Delegate*) (in ***) 128
14 *** base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) (in ***) 144
15 *** base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) (in ***) 236
16 *** base::RunLoop::Run() (in ***) 384
17 *** base::Thread::ThreadMain() (in ***) 428
18 *** base::PlatformThread::Detach(base::PlatformThreadHandle) (in ***) 260
19 libsystem_pthread.dylib __pthread_start (in libsystem_pthread.dylib) 148
Thread 10 crashed with arm64 Thread State:
pc: 0x00000001820a6f5c fp: 0x0000000170641bd0 sp: 0x0000000170641b10 x0: 0x0000000000000000 x1: 0x0000000000000000 x2: 0x0000000000000002 x3: 0x0000000170641b18 x4: 0x0000000000000002 x5: 0x0000000000000000 x6: 0x0000000000000000 x7: 0x0000000000000403 x8: 0x00000000fffffffe x9: 0x0000000000000000 x10: 0x00000000fffffffe x11: 0x0000000000000005 x12: 0x00000002838192b8 x13: 0x0000004000000001 x14: 0x001ffe8000000000 x15: 0x001ffe8000000000 x16: 0x0000000000000177 x17: 0x6ae1000283819280 x18: 0x0000000000000000 x19: 0x0000000283819280 x20: 0x0000000000000001 x21: 0x001ffea400007501 x22: 0x001ffea400000001 x23: 0x0000000170641dd8 x24: 0x0000000170641db8 x25: 0x0000000170641d98 x26: 0x0000000000000001 x27: 0x00000001dc032000 x28: 0x00000001dc032000 lr: 0x0000000182091df8 cpsr: 0x0000000080001000
Binary Images:
0x1b8e41000 - 0x1b8e75000 libsystem_kernel.dylib arm64e <d2476f74d204348d8d386165d0485c7c> /usr/lib/system/libsystem_kernel.dylib
0x1a1cd9000 - 0x1a1ce4000 libsystem_notify.dylib arm64e <ad98a60defce3925a97c072887cf36be> /usr/lib/system/libsystem_notify.dylib
0x18f197000 - 0x18f24c000 IOKit arm64e <08dae3e208c13cf6b8d13854b3ee0d77> /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit
0x18480d000 - 0x186090000 UIKitCore arm64e <0e2d8679d5f13c0390107f6ce3662789> /System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
0x18206b000 - 0x1820b1000 libdispatch.dylib arm64e <959cd6e40ce73022b73c8b36f79f4745> /usr/lib/system/libdispatch.dylib
0x182363000 - 0x1827b7000 CoreFoundation arm64e <6174789ae88c3f5cba39de2e9edc0750> /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
0x19db92000 - 0x19db9b000 GraphicsServices arm64e <0f7424f6bde5311aa3fac0e0c4c28d72> /System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
0x100104000 - 0x10faf8000 *** arm64 <fa0329eae50938c7b09519a50ba29c1e> /private/var/containers/Bundle/Application/4842390D-E12A-47FA-B586-DB4661DE6BEA/***.app/***
0x18f2eb000 - 0x18f5f7000 CoreMotion arm64e <9d82cede6b9d36b3a8f8ba0c9782d328> /System/Library/Frameworks/CoreMotion.framework/CoreMotion
0x1f282c000 - 0x1f2838000 libsystem_pthread.dylib arm64e <bc1ce0c6a9f2396b9afb623d3acd5881> /usr/lib/system/libsystem_pthread.dylib
0x183b8d000 - 0x183e92000 Foundation arm64e <efbca2ff8b8c3227abbc154ba851d23c> /System/Library/Frameworks/Foundation.framework/Foundation
0x182b79000 - 0x18303e000 CFNetwork arm64e <570aad29ce5c3cd9ab01ad21e1440ddb> /System/Library/Frameworks/CFNetwork.framework/CFNetwork
0x19a9a7000 - 0x19aa0b000 libc++.1.dylib arm64e <ad83bb4ecfd63d39a9e2b8e115bef247> /usr/lib/libc++.1.dylib
0x18d2ae000 - 0x18e55b000 JavaScriptCore arm64e <3993ffc446eb3e7fa3dc814e1863b585> /System/Library/Frameworks/JavaScriptCore.framework/JavaScriptCore
0x18b6e3000 - 0x18b70d000 AudioSession arm64e <abd54d35666937df90b922ddf1183098> /System/Library/PrivateFrameworks/AudioSession.framework/AudioSession
0x18cd34000 - 0x18cfc0000 AudioToolbox arm64e <a1e75af5046b3c8a870e0dcb43881f33> /System/Library/Frameworks/AudioToolbox.framework/AudioToolbox
0x19b28a000 - 0x19b2be000 libAudioToolboxUtility.dylib arm64e <08c9eae3a24730179c6af1f2ffb65fc1> /usr/lib/libAudioToolboxUtility.dylib
0x1f2847000 - 0x1f287f000 libxpc.dylib arm64e <e8a600510c6835aeaefd9d97cc7f2696> /usr/lib/system/libxpc.dylib
0x1bdb8e000 - 0x1bdb92000 AppTrackingTransparency arm64e <422d252d95b33c75beeb72ff296a459c> /System/Library/Frameworks/AppTrackingTransparency.framework/AppTrackingTransparency
0x1bdb55000 - 0x1bdb57000 AdSupport arm64e <9cd6f87a74e731e6a90b109f16e19a6d> /System/Library/Frameworks/AdSupport.framework/AdSupport
0x19c9fc000 - 0x19ca15000 libsystem_trace.dylib arm64e <e47c51bb9d5a3882a6bef744a30cce80> /usr/lib/system/libsystem_trace.dylib
0x18303e000 - 0x183b0f000 libnetwork.dylib arm64e <d810c68913393fc696e8196b9901e4dc> /usr/lib/libnetwork.dylib
0x18b138000 - 0x18b2aa000 Security arm64e <7842bf757629334795a6954ea28435cc> /System/Library/Frameworks/Security.framework/Security
I'm building a RSS parser in Swift for MacOS. It won't use any windows, everything will be shown in the Menu Bar.
I have a problem where I'm parsing multiple URL:s using Alamofire and AlamofireRSSParser and I would like to add the result into a list and thereafter sort the articles from the feed according to the date it was published.
For now it works and everything loads into the sub menu (NSMenu) and into the NSStatusBar but when I try load all the articles from the feeds then list returns empty.
I'm guessing this occurs because of Alamofire runs async. If that's the problem do I have to write my own parser or can I run a separate thread handling Alamofires url request and AlamofireRSSparser parsing?
I've tried to execute the URL request and RSS/XML parsing using DispatchQueue to make the call to loadRSS wait until the list has been filled but alas no luck.
This is how the code looks for now. The program loads all the feeds from a local xml file where I have separated the different using a tag called category. The categories can be seen in the picture "Sport", "Ekonomi" and so on. Each category can hold a different amount of URL:s. Each URL are sent to the AlamofireRSS parser and the result is returned back into the NSMenu that I sent in as a parameter (the line "let sub = loadRss(outline: outline, subMenu: sub"). The NSMenu is then added as a submenu for each category, so the category named "Sport" will only show sport articles.
If I try to print the NSMenu "sub" then it's always empty and also if I change the output from loadRSS to a list instead of NSMenu, the list is always empty even though the list is filled in loadRSS (if I use list.append where I now use subMenu.addItem()).
What should I do to be able to sync the parsing of the URL:s with the return of a list so I can sort the resulting articles, and also how is it possible for the NSMenu to print empty and still be able to display the articles in the Menu Bar?
Sorry if the code is bad, it's my first Swift project.
///Used to read the RSS. Is called when the user presses the "Refresh item"
@objc func refresh() {
createMenu()
for i in 0...categories.endIndex-1 {
var sub = NSMenu()
var categoryItem = NSMenuItem()
categoryItem.title = categories[i].title
for outline in categories[i].outlines {
let sub = loadRss(outline: outline, subMenu: sub)
print(sub.items)
}
categoryItem.submenu = sub
categoryItem.target = self
statusBarMenu.addItem(categoryItem)
statusItem?.menu = statusBarMenu
}
statusBarMenu.addItem(quitItem)
statusBarMenu.addItem(refreshItem)
}
func laodRss(outline: Outline, subMenu: NSMenu) -> NSMenu {
var articleList = [NSMenuItem]()
let url = URL(string: outline.xmlUrl)!
AF.request(url).responseRSS() { (response) -> Void in
if let feed: RSSFeed = response.value {
for item in feed.items {
let article = NSMenuItem()
let timeString = self.formatDate(item: item)
if timeString != "" {
var title = self.shortenText(item: item.title!)
title = title + " " + timeString
let someObj: NSString = item.link! as NSString
article.representedObject = someObj
article.action = #selector(self.openBrowser(urlSender:))
article.title = title
//// Get the url from the article and add /favicon.ico to get the image
//// Will add the image to each article to indicate the source
let url = URL(string: outline.icon)
self.getData(from: url!) { data, response, error in
guard let data = data, error == nil else { return }
DispatchQueue.main.async() { [weak self] in
article.image = NSImage(data: data)
article.image?.size = CGSize(width: 15, height: 15)
}
}
subMenu.addItem(article)
}
}
}
}
return subMenu
}
I have searched but cannot find an example of this.
In my example I use playground to nest for-loops in a function called from within DispatchQueue.
I find many roadblocks:
//import AppKit // playground doesn't recognize AppKit?!
import Dispatch
import Foundation
var comboCount:NSKeyValueObservation?
//class viewContr: NSViewController {
@IBOutlet weak var progressBar: NSProgressIndicator!
// deinit { comboCount?.invalidate() }
@IBAction func calcStuff() {
DispatchQueue.global(qos: .userInitiated).async {
let combos = possibleCombos()
DispatchQueue.main.async {
for word in combos {
word.print0b8()
}
}
}
}
//}
func possibleCombos() -> [Int8] {
var combos = [Int8]()
for a in [0, 1] {
for b in [0, 1] {
for c in [0, 1] {
for d in [0, 1] {
combos.append(Int8(d | (c << 1) | (b << 2) | (a << 3)) )
comboCount = combos.count/16 as! NSKeyValueObservation
// known total combos = 16
// How do I pass combos.count out to a progress bar?
}
}
}
}
return combos
}
extension Int8 {func print0b8() {print("0b" + pad(string: String(self, radix: 2), toSize: 4))}}
func pad(string : String, toSize: Int) -> String {var padded = string;for _ in 0..<(toSize - string.count) {padded = "0" + padded};return padded}
Removing the @IB obstacles and the attempted declaration of a ViewController does produce output, but can't be used with a progress bar, e.g.,
import Dispatch
import Foundation
DispatchQueue.global(qos: .userInitiated).async {
let combos = possibleCombos()
DispatchQueue.main.async {
for word in combos {
word.print0b8()
}
}
}
func possibleCombos() -> [Int8] {
var combos = [Int8]()
for a in [0, 1] {
for b in [0, 1] {
for c in [0, 1] {
for d in [0, 1] {
combos.append(Int8(d | (c << 1) | (b << 2) | (a << 3)) )
// known total combos = 16
// How do I pass combos.count out to a progress bar?
}
}
}
}
return combos
}
extension Int8 {func print0b8() {print("0b" + pad(string: String(self, radix: 2), toSize: 4))}}
func pad(string : String, toSize: Int) -> String {var padded = string;for _ in 0..<(toSize - string.count) {padded = "0" + padded};return padded}
In my actual App, i.e., not this playground, I have a ProgressBar in my storyboard and an IBoutlet declared in my view controller. I just can't find how to pass a value out of "possibleCombos()" and into the NSProgressIndicator.
What I have read suggests a delegate but reading about delegates hasn't helped. I need an example.
Thanks.
Docs say: "For serial tasks, set the target of your serial queue to one of the global concurrent queues"
but how exactly?
DispatchQueue(label: "", target: .global(qos: .background))
// or
DispatchQueue(label: "", qos: .background, target: .global(qos: .background))
or is it the same?
context:
We use quite a few serial queues in our app. In general each service (e.g. analytics, downloading, etc) has it's own serial queue to sync. access to it's resources.
Post not yet marked as solved
Hey! Recently, our AppCenter statistics system has received a huge number of crashes of the following content:
libdispatch.dylib
dispatch_mach_send_with_result_and_wait_for_reply
libxpc.dylib
xpc_connection_send_message_with_reply_sync
RunningBoardServices
-[RBSXPCMessage sendToConnection:error:]
RunningBoardServices
-[RBSXPCMessage invokeOnConnection:withReturnCollectionClass:entryClass:error:]
RunningBoardServices
-[RBSConnection acquireAssertion:error:]
RunningBoardServices
-[RBSAssertion acquireWithError:]
CFNetwork
CFURLProtectionSpaceGetServerTrust
CFNetwork
CFHTTPCookieCopyPath
libdispatch.dylib
_dispatch_block_async_invoke2
libdispatch.dylib
_dispatch_client_callout
libdispatch.dylib
_dispatch_lane_serial_drain
libdispatch.dylib
_dispatch_lane_invoke
libdispatch.dylib
_dispatch_workloop_worker_thread
libsystem_pthread.dylib
_pthread_wqthread
libsystem_pthread.dylib
start_wqthread
Has anyone met this? I can't figure out what exactly might be causing such a failure. When testing the application on our AppleTV, there are no glitches.