Can't obtain output buffer from iOS camera in Kotlin Multiplatform - kotlin-multiplatform

I've got a Kotlin Multiplatform multi-module project and one module deals with the camera. I've separated Android and iOS sourcesets for this specific module. Using Kotlin native for iOS, I can succesfully add a video input, a video output and show the preview in a layer, but I can't manage to get the sample buffer in the AVCaptureVideoDataOutputSampleBufferDelegateProtocol delegate.
I'm having this error:
Uncaught Kotlin exception: kotlin.native.IncorrectDereferenceException: illegal attempt to access non-shared <object>#8121d008 from other thread
at 0 MyFramework 0x000000010118fd3c kfun:kotlin.Throwable#<init>(kotlin.String?){} + 92
at 1 MyFramework 0x0000000101188cf0 kfun:kotlin.Exception#<init>(kotlin.String?){} + 88
at 2 MyFramework 0x000000010118883c kfun:kotlin.RuntimeException#<init>(kotlin.String?){} + 88
at 3 MyFramework 0x00000001011b7074 kfun:kotlin.native.IncorrectDereferenceException#<init>(kotlin.String){} + 88
at 4 MyFramework 0x00000001011ba8cc ThrowIllegalObjectSharingException + 428
at 5 MyFramework 0x00000001015fe100 TryAddHeapRef + 0
at 6 MyFramework 0x00000001015fddc4 _ZN27BackRefFromAssociatedObject9tryAddRefEv + 108
at 7 MyFramework 0x00000001015ed7f4 _ZN12_GLOBAL__N_113_tryRetainImpEP11objc_objectP13objc_selector + 64
at 8 libobjc.A.dylib 0x00000002202f1f94 objc_loadWeakRetained + 348
at 9 libobjc.A.dylib 0x00000002202f2060 objc_loadWeak + 20
at 10 AVFoundation 0x00000002271f73b8 <redacted> + 32
at 11 libdispatch.dylib 0x00000001049e8de4 _dispatch_client_callout + 16
at 12 libdispatch.dylib 0x00000001049f7fe4 _dispatch_sync_invoke_and_complete + 124
at 13 AVFoundation 0x00000002271f72c8 <redacted> + 164
at 14 AVFoundation 0x00000002271f715c <redacted> + 36
at 15 AVFoundation 0x00000002271d7fa4 <redacted> + 124
at 16 AVFoundation 0x00000002271d7ce8 <redacted> + 100
at 17 CoreMedia 0x00000002246ffdfc <redacted> + 280
at 18 CoreMedia 0x000000022471d4cc <redacted> + 224
at 19 libdispatch.dylib 0x00000001049e8de4 _dispatch_client_callout + 16
at 20 libdispatch.dylib 0x00000001049ec1e0 _dispatch_continuation_pop + 528
at 21 libdispatch.dylib 0x00000001049fecac _dispatch_source_invoke + 1864
at 22 libdispatch.dylib 0x00000001049f0cd8 _dispatch_lane_serial_drain + 288
at 23 libdispatch.dylib 0x00000001049f1bb4 _dispatch_lane_invoke + 516
at 24 libdispatch.dylib 0x00000001049f0cd8 _dispatch_lane_serial_drain + 288
at 25 libdispatch.dylib 0x00000001049f1b7c _dispatch_lane_invoke + 460
at 26 libdispatch.dylib 0x00000001049fbc18 _dispatch_workloop_worker_thread + 1220
at 27 libsystem_pthread.dylib 0x0000000220d260f0 _pthread_wqthread + 312
at 28 libsystem_pthread.dylib 0x0000000220d28d00 start_wqthread + 4
I guess is related to threading problems, maybe when the images are sendded to the delegate, but I'm not sure. I tried to use #ThreadLocal with no success.
This is the code:
class MyClass(val listener: MyListener) {
...
private val sampleDelegate: AVCaptureVideoDataOutputSampleBufferDelegateProtocol = object : NSObject(), AVCaptureVideoDataOutputSampleBufferDelegateProtocol {
override fun captureOutput(output: AVCaptureOutput, didOutputSampleBuffer: CMSampleBufferRef?, fromConnection: AVCaptureConnection) {
//Not called due to previous error
}
}
...
fun addVideoOutput(captureDevicePosition: AVCaptureDevicePosition) {
val videoOutput = AVCaptureVideoDataOutput()
val myqueue = dispatch_queue_create("cameraQueue", null)
videoOutput.setSampleBufferDelegate(sampleDelegate, myqueue)
val format = kCVPixelFormatType_32BGRA
videoOutput.videoSettings = NSDictionary.dictionaryWithObject(
NSNumber.numberWithUnsignedInt(format),
kCVPixelBufferPixelFormatTypeKey as NSCopyingProtocol
)
if (captureSession.canAddOutput(videoOutput)) {
captureSession.addOutput(videoOutput)
}
val conn = videoOutput.connectionWithMediaType(AVMediaTypeVideo)
if (conn!!.isVideoOrientationSupported()) {
conn.videoOrientation = captureDevicePosition
}
videoOutput.alwaysDiscardsLateVideoFrames = true
captureSession.sessionPreset = AVCaptureSessionPresetHigh
}

Using
val myqueue = dispatch_get_main_queue()
solved the problem

Related

CoreData _NSIsNSSet EXC_BAD_ACCESS KERN_INVALID_ADDRESS - crash on app launch

We are getting this crash on multiple devices but cannot figure out where it originates from. The main thread is crashing.
Stack trace:
Crashed: com.apple.main-thread
0 libobjc.A.dylib 0x193dfd58c object_getMethodImplementation + 20
1 CoreFoundation 0x1940f6928 _NSIsNSSet + 40
2 CoreFoundation 0x193fc2c04 -[NSMutableSet unionSet:] + 112
3 CoreData 0x198abe014 -[_NSFaultingMutableSet willReadWithContents:] + 668
4 CoreData 0x198ae4280 -[_NSFaultingMutableSet count] + 32
5 CoreData 0x198be1bb4 __107-[NSManagedObjectContext(_NestedContextSupport) newValueForRelationship:forObjectWithID:withContext:error:]_block_invoke + 360
6 CoreData 0x198be2e70 internalBlockToNSManagedObjectContextPerform + 104
7 libdispatch.dylib 0x193d8b5ac _dispatch_client_callout + 20
8 libdispatch.dylib 0x193d9843c _dispatch_async_and_wait_invoke + 96
9 libdispatch.dylib 0x193d8b5ac _dispatch_client_callout + 20
10 libdispatch.dylib 0x193d977d4 _dispatch_main_queue_callback_4CF + 832
11 CoreFoundation 0x1940648d4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
12 CoreFoundation 0x19405f58c __CFRunLoopRun + 1692
13 CoreFoundation 0x19405ebc8 CFRunLoopRunSpecific + 480
14 GraphicsServices 0x19e4475cc GSEventRunModal + 164
15 UIKitCore 0x198211744 UIApplicationMain + 1936
16 My App 0x100b37324 main + 16 (main.m:16)
17 libdyld.dylib 0x193edb384 start + 4
At the same time, a background thread operating in a PrivateQueue ManagedObjectContext is busy accessing a ManagedObject via awakeFromFetch, stack trace of this thread:
NSManagedObjectContext 0x28066c700
0 libsystem_kernel.dylib 0x1b09617e4 __ulock_wait + 8
1 libdispatch.dylib 0x1b081bf48 _dlock_wait + 56
2 libdispatch.dylib 0x1b081bcf4 _dispatch_thread_event_wait_slow + 56
3 libdispatch.dylib 0x1b0828618 __DISPATCH_WAIT_FOR_QUEUE__ + 336
4 libdispatch.dylib 0x1b0828204 _dispatch_sync_f_slow + 144
5 CoreData 0x1b56686cc _perform + 200
6 CoreData 0x1b558e2c4 -[NSManagedObjectContext(_NestedContextSupport) newValueForRelationship:forObjectWithID:withContext:error:] + 156
7 CoreData 0x1b555033c -[NSFaultHandler retainedFulfillAggregateFaultForObject:andRelationship:withContext:] + 428
8 CoreData 0x1b554df10 -[_NSFaultingMutableSet willReadWithContents:] + 408
9 CoreData 0x1b55ea5bc -[_NSFaultingMutableSet allObjects] + 32
10 My App 0x1044fdc3c PSUser.isAdmin.getter + 286 (PSUser.swift:286)
11 My App 0x1044fdb04 #objc PSUser.isAdmin.getter + 4309900036 (<compiler-generated>:4309900036)
12 My App 0x1044fc694 PSUser.initCurrentTeam() + 212 (PSUser.swift:212)
13 My App 0x1044fcbc0 #objc PSUser.initCurrentTeam() + 4309896128 (<compiler-generated>:4309896128)
14 My App 0x1044fc658 #objc PSUser.awakeFromFetch() + 4309894744 (<compiler-generated>:4309894744)
15 CoreData 0x1b56520e4 _PFFaultHandlerFulfillFault + 3168
16 CoreData 0x1b5650ab0 _PFFaultHandlerLookupRow + 908
17 CoreData 0x1b56527fc _PF_FulfillDeferredFault + 260
18 CoreData 0x1b5666a2c _pvfk_header + 120
19 CoreData 0x1b5663218 _sharedIMPL_pvfk_core + 32
20 My App 0x10438918c +[PSAppSettings isAutoPilotAllowed:] + 97 (PSAppSettings.m:97)
21 My App 0x1043fbb9c LocationTracker.updateTrackingState(user:) + 1120 (LocationTracker.swift:1120)
22 My App 0x104413b4c partial apply for closure #1 in LocationTracker.store(filteredLocations:) + 1275 (LocationTracker.swift:1275)
23 My App 0x1043bae3c thunk for #escaping #callee_guaranteed () -> () + 4308577852 (<compiler-generated>:4308577852)
24 CoreData 0x1b566b650 developerSubmittedBlockToNSManagedObjectContextPerform + 164
25 libdispatch.dylib 0x1b081b5ac _dispatch_client_callout + 20
26 libdispatch.dylib 0x1b0821a64 _dispatch_lane_serial_drain + 568
27 libdispatch.dylib 0x1b0822498 _dispatch_lane_invoke + 400
28 libdispatch.dylib 0x1b082ba5c _dispatch_workloop_worker_thread + 584
29 libsystem_pthread.dylib 0x1b0881718 _pthread_wqthread + 276
30 libsystem_pthread.dylib 0x1b08879c8 start_wqthread + 8
I am not certain if the two stacks are related, or if the background thread is dispatching anything to the main thread (why should it?), but the call newValueForRelationship:forObjectWithID:withContext:error does appear in both stack traces.
The method for awakeFromFetch is initializing a calculated object property currentTeam via the initCurrentTeam() method. This method accesses the teams relationship on that object. Here is the relevant code:
#objc extension PSUser {
override open func awakeFromFetch() {
super.awakeFromFetch()
initCurrentTeam()
}
/**
This method sets the currentTeam by picking
the appropriate team from the `teams` set.
*/
func initCurrentTeam() {
if (isAdmin || isManager), !isEmployee,
var teams = teams?.allObjects as? [PSTeam],
currentTeam == nil {
...
currentTeam = teams.first
}
}
...
}
Enabled com.apple.CoreData.ConcurrencyDebug in Xcode Scheme but Xcode console does not complain. I have not been able to reproduce this issue while debugging in Xcode. The issue is only reported via Crashlytics in production environment.
Any ideas what might be causing this?

Incorrect strange nonsense making iOS Crashlytics reports due to insufficient free ram?

I have a concerning amount of crashes for my iOS app. When I look at the stacktrace I can follow the flow of the stacktrace up until the 3d line 'fetchDeezerTracks(forAlbum)'. When inspecting my code it should be impossible for this line to be even called. the ApplePlayerManager.play method calls the ApplePlayerManager.fetchTrackIds method which calls a NetworkManager's 'fetchAppleMusicTracks' and this method has a networkRequestResponseHandler to deal with the fetched data, but NEVER ever should/could the 'fetchDeezerTracks' method be called.
My question is the following: Is it possible for Crashlytics to give incorrect reports maybe when the device's free RAM is insufficient? Maybe due to memory leaks or something... I just can't make sense out of the crash report so it would help me a lot to know if something else is at play. Some of the free RAM values of the multiple reports (of the same crash) are the following:
233MB (iPad Air 2), 8MB (iPAad 5th gen), 198MB (iPad Mini 2), 332MB (iPad Mini), 71MB (iPad Air 2), 174MB (iPad 5th gen), 223MB (iPad Air 2), 130MB (iPhone6+), 58MB (iPhoneXR), 381MB (iPhoneXSMax), etc.
Are these normal values?
If these are normal values and crashlytics reports are never "corrupted" then I need to make sense of the stacktrace. I'll add my networking code for reference.
Any help very much appreciated! This is driving me mad and crashes keep on piling up.
Crashed: com.apple.root.background-qos
0 MyApp 0x10045da40 closure #2 in ApplePlayerManager.play(album:withTrack:) + 4302494272 (<compiler-generated>:4302494272)
1 MyApp 0x10045d884 closure #1 in closure #1 in ApplePlayerManager.fetchTrackIds(forAlbum:completionHandler:) + 4302493828 (<compiler-generated>:4302493828)
2 MyApp 0x1004da218 specialized NetworkManager.networkRequestResponseHandler(withResponse:completionHandler:retryHandler:) + 4303004184 (<compiler-generated>:4303004184)
3 MyApp 0x1004d9404 closure #1 in NetworkManager.fetchDeezerTracks(forAlbum:withAccessToken:withCompletionHandler:) + 4303000580
4 MyApp 0x1004d8294 closure #1 in NetworkManager.fetchAppleMusicTracks(forAlbumID:withAccessToken:withCompletionHandler:) + 4302996116
5 Alamofire 0x100a73e64 $s9Alamofire15DownloadRequestC8response5queue0D10Serializer17completionHandlerACXDSo012OS_dispatch_E0CSg_xyAA0B8ResponseVy16SerializedObjectQzGctAA0bkF8ProtocolRzlFyycfU_yycfU_AA0bkF0VyypG_Tg5Tm + 132
6 Alamofire 0x100a79d08 $s9Alamofire15DownloadRequestC8response5queue0D10Serializer17completionHandlerACXDSo012OS_dispatch_E0CSg_xyAA0B8ResponseVy16SerializedObjectQzGctAA0bkF8ProtocolRzlFyycfU_yycfU_AA0bkF0VyypG_Tg5TATm + 36
7 Alamofire 0x100a5b3b0 $sIeg_IeyB_TR + 28
8 libdispatch.dylib 0x18f0eb9a8 _dispatch_call_block_and_release + 24
9 libdispatch.dylib 0x18f0ec524 _dispatch_client_callout + 16
10 libdispatch.dylib 0x18f0a156c _dispatch_root_queue_drain + 684
11 libdispatch.dylib 0x18f0a1bf8 _dispatch_worker_thread2 + 124
12 libsystem_pthread.dylib 0x18f13db38 _pthread_wqthread + 212
13 libsystem_pthread.dylib 0x18f140740 start_wqthread + 8
How I fetch my trackIds (NetworkManager)
func fetchAppleMusicTracks(forAlbumID albumID:String,
withAccessToken accessToken:String,
withCompletionHandler completionHandler:#escaping(JSON?)->Void) {
let url = kAppleMusicAlbumURL + albumID
guard let encodedURL = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return completionHandler(nil) }
let headers = [kAppleMusicAuthoritationKey : kAppleMusicBearerKey + accessToken]
Alamofire.request(encodedURL,
method: .get,
parameters: nil,
encoding: URLEncoding.default,
headers: headers).responseJSON(queue: backgroundQueue) {
[weak self]
response in
guard let self = self else { completionHandler(nil); return }
self.networkRequestResponseHandler(withResponse:response,
completionHandler:completionHandler) {
self.fetchAppleMusicTracks(forAlbumID: albumID,
withAccessToken: accessToken,
withCompletionHandler: completionHandler)
}
}
}
my network request handler (NetworkManager):
func networkRequestResponseHandler(withResponse response:DataResponse<Any>,
completionHandler: #escaping(JSON?)->Void,
retryHandler: #escaping()->Void) {
switch response.result {
case .success(let value):
completionHandler(JSON(value))
case .failure(let error):
if self.noConnectionValidator(forError: error, withRetryHandler:retryHandler) { return completionHandler(nil) }
if let status = response.response?.statusCode {
let message = BackendManager.sharedInstance.APIErrorMessageHandler(status: status)
AlertsManager.sharedInstance.displayAlertWithOKButton(forTitle: kGenericErrorTitle,
message: message,
buttonTitle: "Ok")
} else {
AlertsManager.sharedInstance.displayNetworkErrorMessage(withError: error)
}
completionHandler(nil)
}
}
method to fetch tracks (ApplePlayerManager):
private func fetchTrackIds(forAlbum album:String, completionHandler:#escaping([String]?)->Void) {
retrieveAccessToken {
accessToken in
guard let accessToken = accessToken else { completionHandler(nil); return }
NetworkManager.sharedInstance.fetchAppleMusicTracks(forAlbumID: album, withAccessToken: accessToken) {
JSON in
guard let JSON = JSON else {
completionHandler(nil)
return
}
if let tracks = JSON[kAppleMusicDataKey].array?[0][kAppleMusicRelationshipsKey][kAppleMusicTracksKey][kAppleMusicDataKey].array {
let trackIds = tracks.map{ $0[kAppleMusicTrackIdentifierKey].string }.compactMap{ $0 }
completionHandler(trackIds)
} else {
//AlertsManager.sharedInstance.displayAppleMusicCouldNotFetchTracks()
completionHandler(nil)
}
}
}
}
entry-point -> method to play an Apple track (ApplePlayerManager):
override public func play(album:String, withTrack track:Int) {
super.play(album: album, withTrack: track)
guard let streamingManager = streamingManager else { return setup { self.play(album: album, withTrack: track) } }
indexOfLastPlayingItem = track
fetchTrackIds(forAlbum: album) {
[weak self]
trackIds in
guard let self = self else { return }
guard let trackIds = trackIds else {
return //AlertsManager.sharedInstance.displayAppleMusicTracksFetchFailed()
}
self.loadedAlbumTrackIDs = trackIds
if let remainingTracks = self.calculateRemainingTrackList(fromCurrentTrack: track) {
ThreadManager.sharedInstance.executeOnMainThread {
self.play(forStreamingManager: streamingManager, remainingTracks: remainingTracks)
}
}
}
}
EDIT - MORE INFO:
Since my app is using multiple services, I made an abstract PlayerManager singleton class with concrete singleton subclasses for every service. so the PlayerManager.play(track: trackId) will call the correct concrete class method on ApplePlayerManager if beforehand the PlayerManager.service is set to .Apple
I know it looks like somewhere in code the singleton has incorrectly changed service, but again it would not make any sense + I can not reproduce it nor getting a breakpoint hit.
EDIT PART II - ALL THREADS STACKTRACES:
I am getting the suspicion that this might be thread related? Here are all the threads:
Crashed: com.apple.root.background-qos
EXC_BREAKPOINT 0x0000000104cd5a40
Crashed: com.apple.root.background-qos
0 MyApp 0x104cd5a40 closure #2 in ApplePlayerManager.play(album:withTrack:) + 4376304192 (<compiler-generated>:4376304192)
1 MyApp 0x104cd5884 closure #1 in closure #1 in ApplePlayerManager.fetchTrackIds(forAlbum:completionHandler:) + 4376303748 (<compiler-generated>:4376303748)
2 MyApp 0x104d52218 specialized NetworkManager.networkRequestResponseHandler(withResponse:completionHandler:retryHandler:) + 4376814104 (<compiler-generated>:4376814104)
3 MyApp 0x104d51404 closure #1 in NetworkManager.fetchDeezerTracks(forAlbum:withAccessToken:withCompletionHandler:) + 4376810500
4 MyApp 0x104d50294 closure #1 in NetworkManager.fetchAppleMusicTracks(forAlbumID:withAccessToken:withCompletionHandler:) + 4376806036
5 Alamofire 0x105313e64 $s9Alamofire15DownloadRequestC8response5queue0D10Serializer17completionHandlerACXDSo012OS_dispatch_E0CSg_xyAA0B8ResponseVy16SerializedObjectQzGctAA0bkF8ProtocolRzlFyycfU_yycfU_AA0bkF0VyypG_Tg5Tm + 132
6 Alamofire 0x105319d08 $s9Alamofire15DownloadRequestC8response5queue0D10Serializer17completionHandlerACXDSo012OS_dispatch_E0CSg_xyAA0B8ResponseVy16SerializedObjectQzGctAA0bkF8ProtocolRzlFyycfU_yycfU_AA0bkF0VyypG_Tg5TATm + 36
7 Alamofire 0x1052fb3b0 $sIeg_IeyB_TR + 28
8 libdispatch.dylib 0x1b2e9a9a8 _dispatch_call_block_and_release + 24
9 libdispatch.dylib 0x1b2e9b524 _dispatch_client_callout + 16
10 libdispatch.dylib 0x1b2e8165c _dispatch_root_queue_drain + 640
11 libdispatch.dylib 0x1b2e81cd0 _dispatch_worker_thread2 + 112
12 libsystem_pthread.dylib 0x1b2eecb38 _pthread_wqthread + 212
13 libsystem_pthread.dylib 0x1b2eef740 start_wqthread + 8
com.apple.main-thread
com.apple.main-thread
0 libsystem_kernel.dylib 0x1b2fa9198 mach_msg_trap + 8
1 libsystem_kernel.dylib 0x1b2fa860c mach_msg + 72
2 CoreFoundation 0x1b31533b4 __CFRunLoopServiceMachPort + 148
3 CoreFoundation 0x1b314e3e8 __CFRunLoopRun + 1160
4 CoreFoundation 0x1b314dc34 CFRunLoopRunSpecific + 424
5 GraphicsServices 0x1bd29738c GSEventRunModal + 160
6 UIKitCore 0x1b728022c UIApplicationMain + 1932
7 MyApp 0x104cd1060 main + 12 (AppDelegate.swift:12)
8 libdyld.dylib 0x1b2fd5800 start + 4
com.apple.uikit.eventfetch-thread
com.apple.uikit.eventfetch-thread
0 libsystem_kernel.dylib 0x1b2fa9198 mach_msg_trap + 8
1 libsystem_kernel.dylib 0x1b2fa860c mach_msg + 72
2 CoreFoundation 0x1b31533b4 __CFRunLoopServiceMachPort + 148
3 CoreFoundation 0x1b314e3e8 __CFRunLoopRun + 1160
4 CoreFoundation 0x1b314dc34 CFRunLoopRunSpecific + 424
5 Foundation 0x1b3490bcc -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 228
6 Foundation 0x1b3490aac -[NSRunLoop(NSRunLoop) runUntilDate:] + 88
7 UIKitCore 0x1b7322160 -[UIEventFetcher threadMain] + 152
8 Foundation 0x1b35bf9d0 __NSThread__start__ + 848
9 libsystem_pthread.dylib 0x1b2eebd98 _pthread_start + 156
10 libsystem_pthread.dylib 0x1b2eef74c thread_start + 8
com.twitter.crashlytics.ios.MachExceptionServer
com.twitter.crashlytics.ios.MachExceptionServer
0 MyApp 0x104d7b448 CLSProcessRecordAllThreads + 4376982600
1 MyApp 0x104d7b830 CLSProcessRecordAllThreads + 4376983600
2 MyApp 0x104d6b09c CLSHandler + 4376916124
3 MyApp 0x104d66ac4 CLSMachExceptionServer + 4376898244
4 libsystem_pthread.dylib 0x1b2eebd98 _pthread_start + 156
5 libsystem_pthread.dylib 0x1b2eef74c thread_start + 8
com.apple.root.background-qos
com.apple.root.background-qos
0 libsystem_malloc.dylib 0x1b2ec6154 calloc + 98
1 CoreFoundation 0x1b31e23c4 __CFAllocateObject + 20
2 CoreFoundation 0x1b3205b38 __NSDictionaryM_new + 128
3 Foundation 0x1b3586e68 _encodeObject + 964
4 Foundation 0x1b34a2334 -[NSKeyedArchiver _encodeArrayOfObjects:forKey:] + 360
5 Foundation 0x1b3586f58 _encodeObject + 1204
6 MyApp 0x104d372f8 Album.encode(with:) + 4376703736 (<compiler-generated>:4376703736)
7 MyApp 0x104d37354 #objc Album.encode(with:) + 4376703828 (<compiler-generated>:4376703828)
8 Foundation 0x1b3586f58 _encodeObject + 1204
9 Foundation 0x1b34a2334 -[NSKeyedArchiver _encodeArrayOfObjects:forKey:] + 360
10 Foundation 0x1b3586f58 _encodeObject + 1204
11 MyApp 0x104cec884 Series.encode(with:) + 4376397956 (<compiler-generated>:4376397956)
12 MyApp 0x104cec93c #objc Series.encode(with:) + 4376398140 (<compiler-generated>:4376398140)
13 Foundation 0x1b3586f58 _encodeObject + 1204
14 Foundation 0x1b34a2334 -[NSKeyedArchiver _encodeArrayOfObjects:forKey:] + 360
15 Foundation 0x1b3586f58 _encodeObject + 1204
16 MyApp 0x104cfcaf0 User.encode(with:) + 4376464112 (<compiler-generated>:4376464112)
17 MyApp 0x104cfcc64 #objc User.encode(with:) + 4376464484 (<compiler-generated>:4376464484)
18 Foundation 0x1b3586f58 _encodeObject + 1204
19 Foundation 0x1b34a2334 -[NSKeyedArchiver _encodeArrayOfObjects:forKey:] + 360
20 Foundation 0x1b34ccea0 -[NSDictionary(NSDictionary) encodeWithCoder:] + 876
21 Foundation 0x1b3586f58 _encodeObject + 1204
22 Foundation 0x1b34ed5c8 +[NSKeyedArchiver archivedDataWithRootObject:] + 124
23 SwiftyUserDefaults 0x105c9b8c4 $sSo14NSUserDefaultsC010SwiftyUserB0E7archiveyyAC0B3KeyCyxSgG_AGtlF + 292
24 MyApp 0x104d3a7f8 closure #1 in UserManager._cachedSavedUsers.didset + 4376717304 (<compiler-generated>:4376717304)
25 MyApp 0x104d05e10 partial apply for closure #1 in ThreadManager.executeOnMainThread(afterSeconds:withBlock:) + 4376501776 (<compiler-generated>:4376501776)
26 MyApp 0x104d5fc98 thunk for #escaping #callee_guaranteed () -> () + 4376870040 (<compiler-generated>:4376870040)
27 libdispatch.dylib 0x1b2e9a9a8 _dispatch_call_block_and_release + 24
28 libdispatch.dylib 0x1b2e9b524 _dispatch_client_callout + 16
29 libdispatch.dylib 0x1b2e8165c _dispatch_root_queue_drain + 640
30 libdispatch.dylib 0x1b2e81cd0 _dispatch_worker_thread2 + 112
31 libsystem_pthread.dylib 0x1b2eecb38 _pthread_wqthread + 212
32 libsystem_pthread.dylib 0x1b2eef740 start_wqthread + 8
com.apple.NSURLConnectionLoader
com.apple.NSURLConnectionLoader
0 libsystem_kernel.dylib 0x1b2fa9198 mach_msg_trap + 8
1 libsystem_kernel.dylib 0x1b2fa860c mach_msg + 72
2 CoreFoundation 0x1b31533b4 __CFRunLoopServiceMachPort + 148
3 CoreFoundation 0x1b314e3e8 __CFRunLoopRun + 1160
4 CoreFoundation 0x1b314dc34 CFRunLoopRunSpecific + 424
5 CFNetwork 0x1b6412c44 (Missing)
6 Foundation 0x1b35bf9d0 __NSThread__start__ + 848
7 libsystem_pthread.dylib 0x1b2eebd98 _pthread_start + 156
8 libsystem_pthread.dylib 0x1b2eef74c thread_start + 8
com.apple.root.background-qos
com.apple.root.background-qos
0 libsystem_platform.dylib 0x1b2edd948 _platform_memmove + 88
1 libsystem_malloc.dylib 0x1b2ebc628 szone_realloc + 544
2 libsystem_malloc.dylib 0x1b2ec5a9c malloc_zone_realloc + 168
3 libsystem_malloc.dylib 0x1b2ec625c realloc + 196
4 CoreFoundation 0x1b30f3948 __CFSafelyReallocate + 28
5 Foundation 0x1b3555ea0 _NSMutableDataGrowBytes + 344
6 Foundation 0x1b34a2a34 -[NSConcreteMutableData appendBytes:length:] + 340
7 CoreFoundation 0x1b30fcfac writeBytes + 164
8 CoreFoundation 0x1b30fa01c bufferWrite + 320
9 CoreFoundation 0x1b30fd144 _appendString + 264
10 CoreFoundation 0x1b30fa1b8 _appendObject + 348
11 CoreFoundation 0x1b30f99fc __CFBinaryPlistWriteOrPresize + 528
12 Foundation 0x1b34a27d0 -[NSKeyedArchiver finishEncoding] + 528
13 Foundation 0x1b34ed5d8 +[NSKeyedArchiver archivedDataWithRootObject:] + 140
14 SwiftyUserDefaults 0x105c9b8c4 $sSo14NSUserDefaultsC010SwiftyUserB0E7archiveyyAC0B3KeyCyxSgG_AGtlF + 292
15 MyApp 0x104d3a3bc closure #1 in UserManager._cachedActiveUser.didset + 4376716220 (<compiler-generated>:4376716220)
16 MyApp 0x104d05e10 partial apply for closure #1 in ThreadManager.executeOnMainThread(afterSeconds:withBlock:) + 4376501776 (<compiler-generated>:4376501776)
17 MyApp 0x104d5fc98 thunk for #escaping #callee_guaranteed () -> () + 4376870040 (<compiler-generated>:4376870040)
18 libdispatch.dylib 0x1b2e9a9a8 _dispatch_call_block_and_release + 24
19 libdispatch.dylib 0x1b2e9b524 _dispatch_client_callout + 16
20 libdispatch.dylib 0x1b2e8165c _dispatch_root_queue_drain + 640
21 libdispatch.dylib 0x1b2e81cd0 _dispatch_worker_thread2 + 112
22 libsystem_pthread.dylib 0x1b2eecb38 _pthread_wqthread + 212
23 libsystem_pthread.dylib 0x1b2eef740 start_wqthread + 8
AVAudioSession Notify Thread
AVAudioSession Notify Thread
0 libsystem_kernel.dylib 0x1b2fa9198 mach_msg_trap + 8
1 libsystem_kernel.dylib 0x1b2fa860c mach_msg + 72
2 CoreFoundation 0x1b31533b4 __CFRunLoopServiceMachPort + 148
3 CoreFoundation 0x1b314e3e8 __CFRunLoopRun + 1160
4 CoreFoundation 0x1b314dc34 CFRunLoopRunSpecific + 424
5 AVFAudio 0x1bfef65dc GenericRunLoopThread::Entry(void*) + 156
6 AVFAudio 0x1bff47300 CAPThread::Entry(CAPThread*) + 204
7 libsystem_pthread.dylib 0x1b2eebd98 _pthread_start + 156
8 libsystem_pthread.dylib 0x1b2eef74c thread_start + 8
Thread #1
Thread
0 libsystem_kernel.dylib 0x1b2fcb940 __workq_kernreturn + 8
1 libsystem_pthread.dylib 0x1b2eecbc0 _pthread_wqthread + 348
2 libsystem_pthread.dylib 0x1b2eef740 start_wqthread + 8
Thread #2
Thread
0 libsystem_pthread.dylib 0x1b2eef738 start_wqthread + 190
com.apple.root.background-qos
com.apple.root.background-qos
0 CoreFoundation 0x1b3206828 mdict_rehashd + 244
1 CoreFoundation 0x1b30b8f00 -[__NSDictionaryM __setObject:forKey:] + 888
2 Foundation 0x1b35876d8 addValueToTopContainerE + 128
3 Foundation 0x1b3587180 _encodeObject + 1756
4 Foundation 0x1b34a2334 -[NSKeyedArchiver _encodeArrayOfObjects:forKey:] + 360
5 Foundation 0x1b3586f58 _encodeObject + 1204
6 MyApp 0x104d372f8 Album.encode(with:) + 4376703736 (<compiler-generated>:4376703736)
7 MyApp 0x104d37354 #objc Album.encode(with:) + 4376703828 (<compiler-generated>:4376703828)
8 Foundation 0x1b3586f58 _encodeObject + 1204
9 Foundation 0x1b34a2334 -[NSKeyedArchiver _encodeArrayOfObjects:forKey:] + 360
10 Foundation 0x1b3586f58 _encodeObject + 1204
11 MyApp 0x104cec884 Series.encode(with:) + 4376397956 (<compiler-generated>:4376397956)
12 MyApp 0x104cec93c #objc Series.encode(with:) + 4376398140 (<compiler-generated>:4376398140)
13 Foundation 0x1b3586f58 _encodeObject + 1204
14 Foundation 0x1b34a2334 -[NSKeyedArchiver _encodeArrayOfObjects:forKey:] + 360
15 Foundation 0x1b3586f58 _encodeObject + 1204
16 MyApp 0x104cfcaf0 User.encode(with:) + 4376464112 (<compiler-generated>:4376464112)
17 MyApp 0x104cfcc64 #objc User.encode(with:) + 4376464484 (<compiler-generated>:4376464484)
18 Foundation 0x1b3586f58 _encodeObject + 1204
19 Foundation 0x1b34a2334 -[NSKeyedArchiver _encodeArrayOfObjects:forKey:] + 360
20 Foundation 0x1b34ccea0 -[NSDictionary(NSDictionary) encodeWithCoder:] + 876
21 Foundation 0x1b3586f58 _encodeObject + 1204
22 Foundation 0x1b34ed5c8 +[NSKeyedArchiver archivedDataWithRootObject:] + 124
23 SwiftyUserDefaults 0x105c9b8c4 $sSo14NSUserDefaultsC010SwiftyUserB0E7archiveyyAC0B3KeyCyxSgG_AGtlF + 292
24 MyApp 0x104d3a7f8 closure #1 in UserManager._cachedSavedUsers.didset + 4376717304 (<compiler-generated>:4376717304)
25 MyApp 0x104d05e10 partial apply for closure #1 in ThreadManager.executeOnMainThread(afterSeconds:withBlock:) + 4376501776 (<compiler-generated>:4376501776)
26 MyApp 0x104d5fc98 thunk for #escaping #callee_guaranteed () -> () + 4376870040 (<compiler-generated>:4376870040)
27 libdispatch.dylib 0x1b2e9a9a8 _dispatch_call_block_and_release + 24
28 libdispatch.dylib 0x1b2e9b524 _dispatch_client_callout + 16
29 libdispatch.dylib 0x1b2e8165c _dispatch_root_queue_drain + 640
30 libdispatch.dylib 0x1b2e81cd0 _dispatch_worker_thread2 + 112
31 libsystem_pthread.dylib 0x1b2eecb38 _pthread_wqthread + 212
32 libsystem_pthread.dylib 0x1b2eef740 start_wqthread + 8
com.apple.root.background-qos
com.apple.root.background-qos
0 libobjc.A.dylib 0x1b2f12aa8 objc_release + 24
1 libswiftCore.dylib 0x1c0914680 swift_arrayDestroy + 68
2 libswiftCore.dylib 0x1c06d38c8 _DictionaryStorage.deinit + 360
3 libswiftCore.dylib 0x1c06d394c _DictionaryStorage.__deallocating_deinit + 12
4 libswiftCore.dylib 0x1c091e320 _swift_release_dealloc + 28
5 SwiftyJSON 0x105c396d0 $s10SwiftyJSON6unwrap33_4625CC38AABF536BB76490A35D7233C9LLyypypF + 1400
6 SwiftyJSON 0x105c394a4 $s10SwiftyJSON6unwrap33_4625CC38AABF536BB76490A35D7233C9LLyypypF + 844
7 SwiftyJSON 0x105c395d8 $s10SwiftyJSON6unwrap33_4625CC38AABF536BB76490A35D7233C9LLyypypF + 1152
8 SwiftyJSON 0x105c394a4 $s10SwiftyJSON6unwrap33_4625CC38AABF536BB76490A35D7233C9LLyypypF + 844
9 SwiftyJSON 0x105c394a4 $s10SwiftyJSON6unwrap33_4625CC38AABF536BB76490A35D7233C9LLyypypF + 844
10 SwiftyJSON 0x105c394a4 $s10SwiftyJSON6unwrap33_4625CC38AABF536BB76490A35D7233C9LLyypypF + 844
11 SwiftyJSON 0x105c395d8 $s10SwiftyJSON6unwrap33_4625CC38AABF536BB76490A35D7233C9LLyypypF + 1152
12 SwiftyJSON 0x105c394a4 $s10SwiftyJSON6unwrap33_4625CC38AABF536BB76490A35D7233C9LLyypypF + 844
13 SwiftyJSON 0x105c383e4 $s10SwiftyJSON0B0V6objectypvs + 44
14 SwiftyJSON 0x105c49ccc $s10SwiftyJSON0B0V10jsonObjectACyp_tc33_4625CC38AABF536BB76490A35D7233C9LlfCTf4nd_n + 164
15 SwiftyJSON 0x105c49f00 $s10SwiftyJSON0B0VyACypcfCTf4nd_n + 152
16 SwiftyJSON 0x105c381ac $s10SwiftyJSON0B0VyACypcfC + 28
17 MyApp 0x104d521e4 specialized NetworkManager.networkRequestResponseHandler(withResponse:completionHandler:retryHandler:) + 51 (NetworkManager.swift:51)
18 MyApp 0x104d51404 closure #1 in NetworkManager.fetchDeezerTracks(forAlbum:withAccessToken:withCompletionHandler:) + 4376810500
19 MyApp 0x104d50294 closure #1 in NetworkManager.fetchAppleMusicTracks(forAlbumID:withAccessToken:withCompletionHandler:) + 4376806036
20 Alamofire 0x105313e64 $s9Alamofire15DownloadRequestC8response5queue0D10Serializer17completionHandlerACXDSo012OS_dispatch_E0CSg_xyAA0B8ResponseVy16SerializedObjectQzGctAA0bkF8ProtocolRzlFyycfU_yycfU_AA0bkF0VyypG_Tg5Tm + 132
21 Alamofire 0x105319d08 $s9Alamofire15DownloadRequestC8response5queue0D10Serializer17completionHandlerACXDSo012OS_dispatch_E0CSg_xyAA0B8ResponseVy16SerializedObjectQzGctAA0bkF8ProtocolRzlFyycfU_yycfU_AA0bkF0VyypG_Tg5TATm + 36
22 Alamofire 0x1052fb3b0 $sIeg_IeyB_TR + 28
23 libdispatch.dylib 0x1b2e9a9a8 _dispatch_call_block_and_release + 24
24 libdispatch.dylib 0x1b2e9b524 _dispatch_client_callout + 16
25 libdispatch.dylib 0x1b2e8165c _dispatch_root_queue_drain + 640
26 libdispatch.dylib 0x1b2e81cd0 _dispatch_worker_thread2 + 112
27 libsystem_pthread.dylib 0x1b2eecb38 _pthread_wqthread + 212
28 libsystem_pthread.dylib 0x1b2eef740 start_wqthread + 8
com.google.fira.worker
com.google.fira.worker
0 libsqlite3.dylib 0x1b4df32a8 sqlite3_exec + 26552
1 libsqlite3.dylib 0x1b4dee810 sqlite3_exec + 7456
2 libsqlite3.dylib 0x1b4ded6fc sqlite3_exec + 3084
3 libsqlite3.dylib 0x1b4decc3c sqlite3_exec + 332
4 MyApp 0x104e1d0cc -[APMSqliteStore beginTransaction] + 4377645260
5 MyApp 0x104e1cf18 -[APMSqliteStore performTransactionWithError:block:] + 4377644824
6 MyApp 0x104dd9444 -[APMDatabase performTransaction:] + 4377367620
7 MyApp 0x104df2a5c -[APMMeasurement writeEventOnWorkerQueue:] + 4377471580
8 MyApp 0x104df2280 -[APMMeasurement handleEventOnWorkerQueue:] + 4377469568
9 MyApp 0x104df1500 __27-[APMMeasurement logEvent:]_block_invoke + 4377466112
10 MyApp 0x104e06f50 __51-[APMScheduler scheduleOnWorkerQueueBlockID:block:]_block_invoke + 4377554768
11 libdispatch.dylib 0x1b2e9a9a8 _dispatch_call_block_and_release + 24
12 libdispatch.dylib 0x1b2e9b524 _dispatch_client_callout + 16
13 libdispatch.dylib 0x1b2e78b3c _dispatch_lane_serial_drain$VARIANT$armv81 + 564
14 libdispatch.dylib 0x1b2e7954c _dispatch_lane_invoke$VARIANT$armv81 + 396
15 libdispatch.dylib 0x1b2e8284c _dispatch_workloop_worker_thread + 580
16 libsystem_pthread.dylib 0x1b2eecb74 _pthread_wqthread + 272
17 libsystem_pthread.dylib 0x1b2eef740 start_wqthread + 8
(Just a guess)
This reeks of threading issues (you can get odd threading cashes if you try and access/manipulate the same object from different threads, and looking at your code you have escaping closures on escaping closures all over the place), looking through your crash log maybe it has something to do with the UserManager seeing: this UserManager._cachedSavedUsers.didset twice and UserManager._cachedActiveUser.didset too, always followed by some writes.
Even shows up on the thread labeled com.twitter.crashlytics.ios.MachExceptionServer but that could be for any reason, just suspicious given all this other stuff too and that crashlytics is your crash reporting tool..
App will definitely crash (intermittently) if there's some encoding / property manipulation happening on this user manager / an app-wide cache and its not being accessed in a thread safe way

Creating a Kotlin Native Background Dispatcher for Coroutine

I'm currently trying to write a dispatcher for iOS, to run Http requests in the background. My current attempt is the following object:
val runCoroutineDispatcher: CoroutineContext = NsQueueDispatcher
object NsQueueDispatcher: CoroutineDispatcher(){
override fun dispatch(
context: CoroutineContext,
block: Runnable
){
dispatch_async(
dispatch_get_global_queue(
NSNumber(double = DISPATCH_QUEUE_PRIORITY_DEFAULT.toDouble()).integerValue,
0)
) {
block.run()
}
}
}
If I try to use this dispatcher for a coroutine I always get the issue
Uncaught Kotlin exception: kotlin.native.IncorrectDereferenceException: illegal attempt to access non-shared de.ubimax.common.dispatcher.NsGlobalQueueDispatcher.$dispatch$lambda-0$FUNCTION_REFERENCE$1#8147aca8 from other thread
at 0 FrontlineClientCommon 0x00000001012d0fec kfun:kotlin.Throwable.<init>(kotlin.String?)kotlin.Throwable + 92
at 1 FrontlineClientCommon 0x00000001012c9ebc kfun:kotlin.Exception.<init>(kotlin.String?)kotlin.Exception + 88
at 2 FrontlineClientCommon 0x00000001012c9980 kfun:kotlin.RuntimeException.<init>(kotlin.String?)kotlin.RuntimeException + 88
at 3 FrontlineClientCommon 0x00000001012f92dc kfun:kotlin.native.IncorrectDereferenceException.<init>(kotlin.String)kotlin.native.IncorrectDereferenceException + 88
at 4 FrontlineClientCommon 0x00000001012fae84 ThrowIllegalObjectSharingException + 512
at 5 FrontlineClientCommon 0x000000010185cc9c _ZNK16KRefSharedHolder3refEv + 100
at 6 FrontlineClientCommon 0x0000000101879144 Kotlin_Interop_unwrapKotlinObjectHolder + 48
at 7 FrontlineClientCommon 0x00000001017aa184 _knbridge33 + 120
at 8 libdispatch.dylib 0x0000000108bed7fc _dispatch_call_block_and_release + 24
at 9 libdispatch.dylib 0x0000000108beebd8 _dispatch_client_callout + 16
at 10 libdispatch.dylib 0x0000000108bf12d4 _dispatch_queue_override_invoke + 872
at 11 libdispatch.dylib 0x0000000108c00160 _dispatch_root_queue_drain + 376
at 12 libdispatch.dylib 0x0000000108c00a88 _dispatch_worker_thread2 + 156
at 13 libsystem_pthread.dylib 0x00000001a6160f48 _pthread_wqthread + 212
at 14 libsystem_pthread.dylib 0x00000001a6163ad4 start_wqthread + 8
Sample code:
CoroutineScope(runCoroutineDispatcher).launch {
println("Hello World")
}
So far I only could find examples with the usage of dispatch_get_main_queue() instead of dispatch_get_global_queue().

KVO Crashes while using AVPlayer

I use AVPlayer to play remote videos in Swift, but keep getting these crashes showing up
#0
Crashed: com.apple.avfoundation.playerlayer.configuration
EXC_BREAKPOINT 0x000000010522f968
0 libswiftCore.dylib
__hidden#23281_ line 134
specialized _assertionFailure(StaticString, String, file : StaticString, line : UInt, flags : UInt32) -> Never
1
libswiftFoundation.dylib
swift_stdlib_bridgeNSErrorToError + 59336
2 libswiftFoundation.dylib
swift_convertStringToNSString + 559540
3
libswiftFoundation.dylib
swift_stdlib_bridgeNSErrorToError + 61096
4 Foundation
-[NSKeyValueUnnestedProperty _givenPropertiesBeingInitialized:getAffectingProperties:] + 200
5
Foundation
-[NSKeyValueUnnestedProperty _initWithContainerClass:key:propertiesBeingInitialized:] + 152
6 Foundation
NSKeyValuePropertyForIsaAndKeyPathInner + 284
7 Foundation
NSKeyValuePropertyForIsaAndKeyPath + 144
8 Foundation
-[NSObject(NSKeyValueObserverRegistration) addObserver:forKeyPath:options:context:] + 92
9 AVFoundation
-[AVPlayerItem addObserver:forKeyPath:options:context:] + 368
10 AVFoundation
-[AVKVODispatcher startObservingValueAtKeyPath:ofObject:options:usingBlock:] + 136
11 AVFoundation
-[AVKeyPathDependency _startObservingSecondLevelPropertyOnNewCurrentValueForTopLevelDependencyProperty:] + 132
12 AVFoundation
-[AVKeyPathDependencyManager dependencyHostIsFullyInitialized] + 236
13 AVFoundation
-[AVKeyPathFlattener initForObservingValueAtKeyPath:onObject:] + 188
14 AVFoundation
-[AVKVODispatcher startObservingValueAtTwoPartKeyPath:ofObject:options:usingBlock:] + 100
15 AVFoundation
-[AVKVODispatcher(LegacyCallbackMethod) startObservingObject:weakObserver:forTwoPartKeyPath:options:context:] + 152
16 AVFoundation
-[AVPlayerLayer _startObservingPlayer:] + 404
17 libdispatch.dylib
_dispatch_call_block_and_release + 24
18 libdispatch.dylib
_dispatch_client_callout + 16
19 libdispatch.dylib
_dispatch_queue_serial_drain$VARIANT$mp + 528
20 libdispatch.dylib
_dispatch_queue_invoke$VARIANT$mp + 340
21 libdispatch.dylib
_dispatch_root_queue_drain_deferred_wlh$VARIANT$mp + 404
22 libdispatch.dylib
_dispatch_workloop_worker_thread$VARIANT$mp + 644
23 libsystem_pthread.dylib
_pthread_wqthread + 932
24
libsystem_pthread.dylib
start_wqthread + 4
I've used traditional KVO by adding an observer to self and overriding the observeValueForKey function and also tried using the new block-based KVO, but something along the lines of this crash always happens (and yes I always remove observers on deinit). This mostly happens on ios 11 devices but I've never gotten this crash on my own device, so I have no idea how it happens.
Does anyone have any idea why this happens or things I can try to fix it? The crash rate on this keeps going up as I add more videos into the app.

Swift: Accessing JSON received by post request

let task = URLSession.shared.dataTask(with: postRequest) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "NoData")
return
}
let jsonString = String(data: data, encoding: String.Encoding.utf8)!
self.submitView.text = jsonString
}
task.resume()
I'm trying to access the return value of this post request. I set a breakpoint and saw that jsonString does get the correct value. However, which I try to set self.submitView.text to anything, I get this error:
2017-06-21 14:20:16.062815-0400 Button[958:197756] This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.
Stack:(
0 CoreFoundation 0x0000000191c82ff8 <redacted> + 148
1 libobjc.A.dylib 0x00000001906e4538 objc_exception_throw + 56
2 CoreFoundation 0x0000000191c82f28 <redacted> + 0
3 Foundation 0x0000000192874338 <redacted> + 128
4 Foundation 0x00000001926bc9f8 <redacted> + 36
5 UIKit 0x0000000197daf76c <redacted> + 816
6 UIKit 0x0000000197dbb668 <redacted> + 1740
7 UIKit 0x0000000197dbaf84 <redacted> + 828
8 UIKit 0x0000000197df90f4 <redacted> + 256
9 UIKit 0x0000000197df1818 <redacted> + 116
10 UIKit 0x00000001987ec308 <redacted> + 48
11 UIKit 0x0000000197e5d880 <redacted> + 280
12 UIFoundation 0x0000000197cdb238 <redacted> + 7012
13 UIFoundation 0x0000000197cdc0c8 <redacted> + 52
14 UIFoundation 0x0000000197d0eb70 <redacted> + 48
15 UIKit 0x0000000197e5d85c <redacted> + 244
16 UIFoundation 0x0000000197ce0214 <redacted> + 2172
17 UIFoundation 0x0000000197d0b058 <redacted> + 240
18 UIFoundation 0x0000000197d2f474 <redacted> + 160
19 UIFoundation 0x0000000197d2ebb4 <redacted> + 92
20 UIKit 0x0000000197e60500 <redacted> + 252
21 UIKit 0x0000000197e603e4 <redacted> + 196
22 Button 0x0000000100061e24 _TFFC6Button14ViewController12submitTappedFT_T_U_FTGSqV10Foundation4Data_GSqCSo11URLResponse_GSqPs5Error___T_ + 784
23 Button 0x0000000100062468 _TTRXFo_oGSqV10Foundation4Data_oGSqCSo11URLResponse_oGSqPs5Error____XFdCb_dGSqCSo6NSData_dGSqS1__dGSqCSo7NSError___ + 224
24 CFNetwork 0x000000019228c34c <redacted> + 32
25 CFNetwork 0x00000001922a4048 <redacted> + 148
26 Foundation 0x0000000192751814 <redacted> + 16
27 Foundation 0x0000000192696770 <redacted> + 96
28 Foundation 0x0000000192686b28 <redacted> + 612
29 Foundation 0x0000000192753bb0 <redacted> + 228
30 libdispatch.dylib 0x0000000100a6da10 _dispatch_client_callout + 16
31 libdispatch.dylib 0x0000000100a7b2e8 _dispatch_queue_serial_drain + 1140
32 libdispatch.dylib 0x0000000100a71634 _dispatch_queue_invoke + 852
33 libdispatch.dylib 0x0000000100a7d630 _dispatch_root_queue_drain + 552
34 libdispatch.dylib 0x0000000100a7d39c _dispatch_worker_thread3 + 140
35 libsystem_pthread.dylib 0x0000000190d43100 _pthread_wqthread + 1096
36 libsystem_pthread.dylib 0x0000000190d42cac start_wqthread + 4
)
2017-06-21 14:20:16.085280-0400 Button[958:197756] This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.
Stack:(
0 CoreFoundation 0x0000000191c82ff8 <redacted> + 148
1 libobjc.A.dylib 0x00000001906e4538 objc_exception_throw + 56
2 CoreFoundation 0x0000000191c82f28 <redacted> + 0
3 Foundation 0x0000000192874338 <redacted> + 128
4 Foundation 0x00000001926bc9f8 <redacted> + 36
5 UIKit 0x0000000197eb18e0 <redacted> + 564
6 UIKit 0x0000000197db0138 <redacted> + 224
7 UIKit 0x0000000197daf8d0 <redacted> + 120
8 Foundation 0x00000001926bca7c <redacted> + 168
9 UIKit 0x0000000197daf76c <redacted> + 816
10 UIKit 0x0000000197dbb668 <redacted> + 1740
11 UIKit 0x0000000197dbaf84 <redacted> + 828
12 UIKit 0x0000000197df90f4 <redacted> + 256
13 UIKit 0x0000000197df1818 <redacted> + 116
14 UIKit 0x00000001987ec308 <redacted> + 48
15 UIKit 0x0000000197e5d880 <redacted> + 280
16 UIFoundation 0x0000000197cdb238 <redacted> + 7012
17 UIFoundation 0x0000000197cdc0c8 <redacted> + 52
18 UIFoundation 0x0000000197d0eb70 <redacted> + 48
19 UIKit 0x0000000197e5d85c <redacted> + 244
20 UIFoundation 0x0000000197ce0214 <redacted> + 2172
21 UIFoundation 0x0000000197d0b058 <redacted> + 240
22 UIFoundation 0x0000000197d2f474 <redacted> + 160
23 UIFoundation 0x0000000197d2ebb4 <redacted> + 92
24 UIKit 0x0000000197e60500 <redacted> + 252
25 UIKit 0x0000000197e603e4 <redacted> + 196
26 Button 0x0000000100061e24 _TFFC6Button14ViewController12submitTappedFT_T_U_FTGSqV10Foundation4Data_GSqCSo11URLResponse_GSqPs5Error___T_ + 784
27 Button 0x0000000100062468 _TTRXFo_oGSqV10Foundation4Data_oGSqCSo11URLResponse_oGSqPs5Error____XFdCb_dGSqCSo6NSData_dGSqS1__dGSqCSo7NSError___ + 224
28 CFNetwork 0x000000019228c34c <redacted> + 32
29 CFNetwork 0x00000001922a4048 <redacted> + 148
30 Foundation 0x0000000192751814 <redacted> + 16
31 Foundation 0x0000000192696770 <redacted> + 96
32 Foundation 0x0000000192686b28 <redacted> + 612
33 Foundation 0x0000000192753bb0 <redacted> + 228
34 libdispatch.dylib 0x0000000100a6da10 _dispatch_client_callout + 16
35 libdispatch.dylib 0x0000000100a7b2e8 _dispatch_queue_serial_drain + 1140
36 libdispatch.dylib 0x0000000100a71634 _dispatch_queue_invoke + 852
37 libdispatch.dylib 0x0000000100a7d630 _dispatch_root_queue_drain + 552
38 libdispatch.dylib 0x0000000100a7d39c _dispatch_worker_thread3 + 140
39 libsystem_pthread.dylib 0x0000000190d43100 _pthread_wqthread + 1096
40 libsystem_pthread.dylib 0x0000000190d42cac start_wqthread + 4
)
2017-06-21 14:20:16.088842-0400 Button[958:197756] *** Assertion failure in void _UIPerformResizeOfTextViewForTextContainer(NSLayoutManager *, UIView<NSTextContainerView> *, NSTextContainer *, NSUInteger)(), /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIFoundation/UIFoundation-491.7/UIFoundation/TextSystem/NSLayoutManager_Private.m:1577
2017-06-21 14:20:16.089727-0400 Button[958:197756] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Only run on the main thread!'
*** First throw call stack:
(0x191c82fe0 0x1906e4538 0x191c82eb4 0x19271a78c 0x197cd93f8 0x197cd90d8 0x197d07e88 0x197d0b188 0x197d2f474 0x197d2ebb4 0x197e60500 0x197e603e4 0x100061e24 0x100062468 0x19228c34c 0x1922a4048 0x192751814 0x192696770 0x192686b28 0x192753bb0 0x100a6da10 0x100a7b2e8 0x100a71634 0x100a7d630 0x100a7d39c 0x190d43100 0x190d42cac)
libc++abi.dylib: terminating with uncaught exception of type NSException
It seems like I can't assign self.submitView.text to anything inside the scope of "task". Any ideas why?
Edit:
Here is what the server returns upon sending a request.
"{\"raw\":\"schedule for John in New York on Monday\",\"location\":\"New York\",\"date\":\"Mon, June 26\",\"name\":\"john\",\"errorResponse\":null,\"stripTest\":\"for John in new york on Monday\"}"
This is what my code looks like:
do {
let info = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any]
DispatchQueue.main.async {
self.submitView.text = info?["name"] as! String
}
} catch {
DispatchQueue.main.async {
self.submitView.text = "ERROR"
}
}
"ERROR" is no longer printing, but "info" seems to have 0 key/value pairs, thus nothing prints.
UPDATE:
print(try? JSONSerialization.jsonObject(with: data, options: [])) prints "nil"
The latter prints:
Optional("\"{\\\"raw\\\":\\\"Schedule for John in New York on Monday\\\",\\\"location\\\":\\\"new york\\\",\\\"date\\\":\\\"6/26/2017 12:00:00 AM\\\",\\\"name\\\":\\\"john\\\",\\\"errorResponse\\\":null,\\\"stripTest\\\":\\\" for john in new york on monday \\\"}\"")
This isn't what prints when I assign it to a text view in the UI.. is it converting the escape sequences to literal characters?
You are setting the text property of the UITextField on a background thread.
You need to ensure that all UI work is done on the main thread, You can do this using DispatchQueue...
DispatchQueue.main.async {
self.submitView.text = jsonString
}
Update:
The data is literally the data that was sent over the network, you will need to convert and deserialise it.
You can do this using the JSON Serialisation class like so:
// I create some dummy JSON string for example purposes
let data = "{ \"name\": \"John Smith\"}".data(using: String.Encoding.utf8)!
if let jsonObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:AnyObject] {
print(jsonObject["name"] as! String)
}
This tries to convert the data into a JSON object, which in Swift is usually cast to a dictionary object.
There are loads of resources on networking with Swift available. One I highly recommend would be iOS Networking with Swift this would take a fair bit of time to go through and learn so here is something that is alot quicker to get through Working with JSON in Swift
UPDATE
This code works for me:
let data = "{\"raw\":\"schedule for John in New York on Monday\",\"location\":\"New York\",\"date\":\"Mon, June 26\",\"name\":\"john\",\"errorResponse\":null,\"stripTest\":\"for John in new york on Monday\"}".data(using: String.Encoding.utf8)!
if let jsonObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:AnyObject] {
print(jsonObject)
print(jsonObject["name"] as! String)
}

Resources