Crashed: com.apple.main-thread partial apply for closure #2 - ios

Crashes are reported into firebase console. Can anyone help me. i am sending data to server using Socket.
Here is crash description:
Crashed: com.apple.main-thread
0 AppName 0x10ef40 partial apply for closure #2 in sendDataRecursively() + 4329697088 (swift:4329697088)
1 AppName 0x23824 thunk for #escaping #callee_guaranteed () -> () + 4328732708 (<compiler-generated>:4328732708)
2 libdispatch.dylib 0x1e68 _dispatch_call_block_and_release + 32
3 libdispatch.dylib 0x3a2c _dispatch_client_callout + 20
4 libdispatch.dylib 0x11f48 _dispatch_main_queue_drain + 928
5 libdispatch.dylib 0x11b98 _dispatch_main_queue_callback_4CF + 44
6 CoreFoundation 0x522f0
CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
7 CoreFoundation 0xc1f4 __CFRunLoopRun + 2532
8 CoreFoundation 0x1f6b8 CFRunLoopRunSpecific + 600
9 GraphicsServices 0x1374 GSEventRunModal + 164
10 UIKitCore 0x513e88 -[UIApplication _run] + 1100
11 UIKitCore 0x2955ec UIApplicationMain + 364
12 AppName 0x48dac main + 17 (AppDelegate.swift:17)
13 ??? 0x1008edce4 (Missing)
Here is my function:
#objc func sendDataRecursively() {
let reachability = try! Reachability()
if reachability.connection != .unavailable {
DispatchQueue.global(qos: .userInitiated).async { //previous .bakground
if self.msgCnt == 127 {
self.msgCnt = 0
}
self.msgCnt += 1
self.sendRequest()
}
} else {
DispatchQueue.main.async {
self.previousStatusWhenDisconnect = self.motionDetectionLbl?.text ?? ""
self.appDelegate.statusLbl?.text = String(format: "%# %#", (self.appDelegate.statusLbl?.text)!, StartVCStringsEnglish.disConnectedString)
}
self.networkTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.checkNetworkRecursively), userInfo: nil, repeats: true)
}
}
Here is the my other function. i am sending data to my Socket function. i did't got the crash but its reported into firebase. Also in firebase has not much more information about the crash. its just show the function name only.
private func sendRequest() {
self.calculateMessageData()
var requestData: Data?
var txData = [UInt8()]
var crc: Int
if self.msgID == Int8(EnMessageType.basicSafetyMessage.rawValue) {
requestData = self.getBasicSafetyMessage()
} else {
requestData = self.getPersonalSafetyMessage()
}
crc = computeCRC(data: requestData!, length: requestData!.count)
// wrap data in 7E, do byte stuffing and add CRC
txData = []
txData.append(0x7E)
for ii in 0..<requestData!.count {
switch requestData![ii] {
case 0x7D:
txData.append(0x7D)
txData.append(0x5D)
break
case 0x7E:
txData.append(0x7D)
txData.append(0x5E)
break
default:
txData.append(requestData![ii])
break
}
}
txData.append((UInt8)(crc >> 8))
txData.append((UInt8)(crc & 0xFF))
txData.append(0x7E)
requestData = (Data)(txData)
if AppSingletonVariable.sharedInstance.isConnected == true { AppSingletonVariable.sharedInstance.mySocket.sendDataToServer(reqData: requestData!)
}
}
Thanks,

You can see from the crash description that there is issue in 2nd closure in sendDataRecursively() function:
DispatchQueue.main.async {
self.previousStatusWhenDisconnect = self.motionDetectionLbl?.text ?? ""
self.appDelegate.statusLbl?.text = String(format: "%# %#", (self.appDelegate.statusLbl?.text)!, StartVCStringsEnglish.disConnectedString)
}
self.networkTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.checkNetworkRecursively), userInfo: nil, repeats: true)
The issue is probably '!' in this expression:
(self.appDelegate.statusLbl?.text)!
If statusLbl is nil, this code crashes. As it was mentioned in comment, it's not safe to force unwrap optionals and this is the reason.
Replace your closure with this:
DispatchQueue.main.async {
self.previousStatusWhenDisconnect = self.motionDetectionLbl?.text ?? ""
if let text = self.appDelegate.statusLbl?.text {
self.appDelegate.statusLbl?.text = String(format: "%# %#", text, StartVCStringsEnglish.disConnectedString)
}
}
self.networkTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.checkNetworkRecursively), userInfo: nil, repeats: true)

Related

Firebase fetching causes crash for some users

When I try to fetch user data from Firebase a crash occurs for some users, I can't reproduce this crash myself but I do have the following crash log:
0 Ski Tracker 0x77bf0 closure #1 in HistoryPresenter.downloadHistory(completionHandler:) + 4340857840 (HistoryPresenter.swift:4340857840)
1 Ski Tracker 0x86c8 closure #1 in FetchFromDatabase.fetchUserHistoryFromDatabase(uid:completionHandler:) + 4340401864 (<compiler-generated>:4340401864)
2 Ski Tracker 0x8604 thunk for #escaping #callee_guaranteed (#guaranteed FIRDataSnapshot) -> () + 4340401668 (<compiler-generated>:4340401668)
3 FirebaseDatabase 0x1df28 __92-[FIRDatabaseQuery observeSingleEventOfType:andPreviousSiblingKeyWithBlock:withCancelBlock:]_block_invoke + 120
4 FirebaseDatabase 0xbf94 __43-[FChildEventRegistration fireEvent:queue:]_block_invoke.11 + 80
5 libdispatch.dylib 0x24b4 _dispatch_call_block_and_release + 32
6 libdispatch.dylib 0x3fdc _dispatch_client_callout + 20
7 libdispatch.dylib 0x127f4 _dispatch_main_queue_drain + 928
8 libdispatch.dylib 0x12444 _dispatch_main_queue_callback_4CF + 44
9 CoreFoundation 0x9a6f8 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
10 CoreFoundation 0x7c058 __CFRunLoopRun + 2036
11 CoreFoundation 0x80ed4 CFRunLoopRunSpecific + 612
12 GraphicsServices 0x1368 GSEventRunModal + 164
13 UIKitCore 0x3a23d0 -[UIApplication _run] + 888
14 UIKitCore 0x3a2034 UIApplicationMain + 340
15 libswiftUIKit.dylib 0x35308 UIApplicationMain(_:_:_:_:) + 104
16 Ski Tracker 0x7160 main + 4340396384 (FriendView.swift:4340396384)
17 ??? 0x1f6938960 (Missing)
If I understand the crash log correctly the code which is causing the crash is within the fetchUserHistoryFromDatabase function:
func fetchUserHistoryFromDatabase(uid : String, completionHandler: #escaping([String : Any]?) -> Void ) {
ref?.child("users").child(uid).child("runData").observeSingleEvent(of: .value, with: { snapshot in
guard let result = snapshot.value as? [String:Any] else {
print("Error no rundata")
completionHandler(nil)
return
}
completionHandler(result)
})
}
This function is called from downloadHistory where potential nil values are handled:
private func downloadHistory(completionHandler: #escaping () -> Void) {
if let id = Auth.auth().currentUser?.uid {
FetchFromDatabase().fetchUserHistoryFromDatabase(uid : id, completionHandler: { [weak self] dict in
if dict != nil {
for run in dict! {
self?.determineTimeStamp(run : run)
}
if !(self!.tempDict.isEmpty) {
let sortedDict = self?.tempDict.keys.sorted(by: { $0 > $1 } )
self?.convertDictToArray(sortedDict: sortedDict!)
}
}
completionHandler()
}
)}
}
Any help here is greatly appreciated.
Remove the force unwrapping from your code. Every ! is an invitation for a crash.
private func downloadHistory(completionHandler: #escaping () -> Void) {
if let id = Auth.auth().currentUser?.uid {
FetchFromDatabase().fetchUserHistoryFromDatabase(uid : id, completionHandler: { [weak self] dict in
guard let self = self else {
completion()
return
}
if let dict = dict {
for run in dict {
self.determineTimeStamp(run : run)
}
if !self.tempDict.isEmpty {
let sortedDict = self.tempDict.keys.sorted(by: { $0 > $1 } )
self.convertDictToArray(sortedDict: sortedDict)
}
}
completionHandler()
}
)}
}
I notice a self! there dangerous, because a user could leave the calling context of the function and since the closure has a capture list of weak self, it should return nil but you are forcing it
try this
private func downloadHistory(completionHandler: #escaping () -> Void) {
if let id = Auth.auth().currentUser?.uid {
FetchFromDatabase().fetchUserHistoryFromDatabase(uid : id, completionHandler: { [weak self] dict in
guard let self = self else { completionHandler()
return }
if let safeDict = dict {
for run in dict {
self.determineTimeStamp(run : run)
}
if (self.tempDict.isEmpty) {
let sortedDict = self.tempDict.keys.sorted(by: { $0 > $1 } )
self.convertDictToArray(sortedDict: sortedDict)
}
}
completionHandler()
}
)}
}

Crash when calling completion handler for `UNUserNotificationCenter`

I'm working on an app that, when receiving a silent push notification; will make two networking calls to get some data, and then use that data to create a local push notification.
This mostly works great in the foreground and the background; with the exception of some occasional crashes that I'm having a difficult time diagnosing.
This is my full implementation for the delegate method that gets called when the silent push notification arrives:
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("Notification received!")
UNUserNotificationCenter.current().delegate = self
let id = updateNotificationID()
let payload = userInfo
guard let ship: String = payload["ship"] as? String else {
return
}
guard let node: String = payload["node"] as? String else {
return
}
guard let graph: String = payload["graph"] as? String else {
return
}
var groupName: String = ""
networkStore.scryForGroupInfo(ship: ship, graph: graph) { groupTitle in
if groupTitle == "" {
//one on one
} else {
//groupchat
groupName = groupTitle
}
networkStore.scryOnNotificationReceipt(ship: ship, node: node, graph: graph) { [self] messageString, author in
let content = UNMutableNotificationContent()
if groupName == "" {
//group chat
content.title = "New Message from \(author)"
let chatShipDict:[String: String] = ["ChatShip": author]
content.userInfo = chatShipDict
} else {
content.title = "\(author) posted in \(groupName)"
let chatShipDict:[String: String] = ["ChatShip": groupName]
content.userInfo = chatShipDict
}
//Don't show a notification for a chat that we're currently in
if airlockStore.selectedChannel != nil {
let author = "~"+author
if airlockStore.selectedChannel.channelShip == author || airlockStore.selectedChannel.channelName == groupName {
completionHandler(.noData)
return
}
} else {
//One on one chat
if groupName == "" {
let author = "~"+author
for channel in airlockStore.unPinnedChannelDataObjects {
if channel.channelShip == author {
notificationChannel = channel
}
}
} else {
//Group chat
for channel in airlockStore.unPinnedChannelDataObjects {
if channel.channelName == groupName {
notificationChannel = channel
}
}
}
}
content.body = messageString
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false)
let request = UNNotificationRequest(identifier: "notification.id.\(id)", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { Error in
print("Showing Notification")
completionHandler(.newData)
}
}
}
}
The crashes seem to occur at the completionHandler(.newData) line.
Here's my stack trace:
Thread 10 name:
Thread 10 Crashed:
0 libdispatch.dylib 0x00000001a0b147b8 dispatch_group_leave.cold.1 + 36 (semaphore.c:303)
1 libdispatch.dylib 0x00000001a0ae0668 dispatch_group_leave + 140 (semaphore.c:0)
2 Pocket 0x000000010464333c partial apply for closure #1 in closure #1 in closure #1 in AppDelegate.application(_:didReceiveRemoteNotification:fetchCompletionHandler:) + 136 (AppDelegate.swift:137)
3 Pocket 0x00000001046419ac thunk for #escaping #callee_guaranteed (#guaranteed Error?) -> () + 44 (<compiler-generated>:0)
4 libdispatch.dylib 0x00000001a0adda84 _dispatch_call_block_and_release + 32 (init.c:1466)
5 libdispatch.dylib 0x00000001a0adf81c _dispatch_client_callout + 20 (object.m:559)
6 libdispatch.dylib 0x00000001a0ae7004 _dispatch_lane_serial_drain + 620 (inline_internal.h:2557)
7 libdispatch.dylib 0x00000001a0ae7c34 _dispatch_lane_invoke + 456 (queue.c:3862)
8 libdispatch.dylib 0x00000001a0af24bc _dispatch_workloop_worker_thread + 764 (queue.c:6589)
9 libsystem_pthread.dylib 0x00000001ecc7e7a4 _pthread_wqthread + 276 (pthread.c:2437)
10 libsystem_pthread.dylib 0x00000001ecc8574c start_wqthread + 8
You say you are making two different network calls.
Are you sure you are not calling the completion handler twice sometimes? Make sure it is only called once.

Why Does CarPlay Crash In Real Car?

I have an audio app and have implemented CarPlay, I've followed this guide to add CarPlay support: https://blog.fethica.com/add-carplay-support-to-swiftradio/#
The app uses the com.apple.developer.playable-content entitlement and Media Player framework, which as far as I know, has been the only way to add CarPlay to audio apps on iOS 13 and below, but is still backwards compatible with iOS 14 (despite there being a new carplay audio framework for iOS 14). All my CarPlay logic is written in an extension of my main AppDelegate (could this be problematic?)
In the simulator, everything has been working fine and the audio plays in the external simulated car display. But my team tested the app in a real car and the application crashes immediately when opened from the car display.
I have the crash log here when tested on iPhone 11 Pro on iOS 14.4:
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000001b88d13cc
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [27455]
Triggered by Thread: 5
Thread 0 name:
Thread 0:
0 libsystem_kernel.dylib 0x00000001d6aa6f5c __ulock_wait + 8
1 libdispatch.dylib 0x00000001a8746794 _dlock_wait + 56 (lock.c:326)
2 libdispatch.dylib 0x00000001a87466c0 _dispatch_once_wait + 124 (lock.c:382)
3 UIKitCore 0x00000001ab1080f8 -[_UIApplicationConfigurationLoader _loadInitializationContext] + 152 (once.h:84)
4 UIKitCore 0x00000001ab108444 -[_UIApplicationConfigurationLoader applicationInitializationContext] + 32 (_UIApplicationConfigurationLoader.m:161)
5 UIKitCore 0x00000001ab0ef05c -[_UIScreenInitialDisplayConfigurationLoader initialDisplayContext] + 180 (UIScreen.m:371)
6 UIKitCore 0x00000001ab0ef348 +[UIScreen initialize] + 128 (UIScreen.m:626)
7 libobjc.A.dylib 0x00000001bdb67c58 CALLING_SOME_+initialize_METHOD + 24 (objc-initialize.mm:384)
8 libobjc.A.dylib 0x00000001bdb6e318 initializeNonMetaClass + 716 (objc-initialize.mm:554)
9 libobjc.A.dylib 0x00000001bdb6f910 initializeAndMaybeRelock(objc_class*, objc_object*, mutex_tt<false>&, bool) + 280 (objc-runtime-new.mm:2221)
10 libobjc.A.dylib 0x00000001bdb7e498 lookUpImpOrForward + 956 (objc-runtime-new.mm:2237)
11 libobjc.A.dylib 0x00000001bdb68524 _objc_msgSend_uncached + 68
12 UIKitCore 0x00000001ab33ef48 -[_UIRemoteKeyboards keyboardWindow] + 52 (_UIRemoteKeyboards.m:2036)
13 UIKitCore 0x00000001ab33cf6c -[_UIRemoteKeyboards allowedToShowKeyboard] + 96 (_UIRemoteKeyboards.m:1588)
14 UIKitCore 0x00000001ab33bda8 -[_UIRemoteKeyboards checkConnection] + 64 (_UIRemoteKeyboards.m:1315)
15 UIKitCore 0x00000001ab338b60 -[_UIRemoteKeyboards init] + 156 (_UIRemoteKeyboards.m:797)
16 UIKitCore 0x00000001ab338ab4 __43+[_UIRemoteKeyboards sharedRemoteKeyboards]_block_invoke + 20 (_UIRemoteKeyboards.m:785)
17 libdispatch.dylib 0x00000001a8745db0 _dispatch_client_callout + 20 (object.m:559)
18 libdispatch.dylib 0x00000001a87475c8 _dispatch_once_callout + 32 (once.c:52)
19 UIKitCore 0x00000001ab338a9c +[_UIRemoteKeyboards sharedRemoteKeyboards] + 176 (once.h:84)
20 UIKitCore 0x00000001ab50ccac _UIApplicationMainPreparations + 1348 (UIApplication.m:4644)
21 UIKitCore 0x00000001ab50c740 UIApplicationMain + 140 (UIApplication.m:4704)
22 MyAppName 0x000000010458fb04 main + 68 (UITextField+Extension.swift:22)
23 libdyld.dylib 0x00000001a87866b0 start + 4
Thread 1:
0 libsystem_pthread.dylib 0x00000001f4608764 start_wqthread + 0
Thread 2:
0 libsystem_pthread.dylib 0x00000001f4608764 start_wqthread + 0
Thread 3 name:
Thread 3:
0 libsystem_kernel.dylib 0x00000001d6a822d0 mach_msg_trap + 8
1 libsystem_kernel.dylib 0x00000001d6a81660 mach_msg + 76 (mach_msg.c:103)
2 libdispatch.dylib 0x00000001a875e888 _dispatch_mach_send_and_wait_for_reply + 528 (mach.c:812)
3 libdispatch.dylib 0x00000001a875ec24 dispatch_mach_send_with_result_and_wait_for_reply + 56 (mach.c:1998)
4 libxpc.dylib 0x00000001f4626e68 xpc_connection_send_message_with_reply_sync + 240 (connection.c:848)
5 BoardServices 0x00000001c2599958 -[BSXPCServiceConnectionMessage _sendSynchronously:] + 332 (BSXPCServiceConnectionMessage.m:129)
6 BoardServices 0x00000001c259a2cc -[BSXPCServiceConnectionMessage sendSynchronouslyWithError:] + 256 (BSXPCServiceConnectionMessage.m:182)
7 BoardServices 0x00000001c2584afc __71+[BSXPCServiceConnectionProxy createImplementationOfProtocol:forClass:]_block_invoke + 824 (BSXPCServiceConnectionProxy.m:274)
8 UIKitServices 0x00000001acb7fc6c -[UISApplicationSupportClient applicationInitializationContextWithParameters:] + 272 (UISApplicationSupportClient.m:77)
9 UIKitCore 0x00000001ab108278 __63-[_UIApplicationConfigurationLoader _loadInitializationContext]_block_invoke_2 + 228 (_UIApplicationConfigurationLoader.m:135)
10 UIKitCore 0x00000001ab108188 __UIAPPLICATION_IS_LOADING_INITIALIZATION_INFO_FROM_THE_SYSTEM__ + 28 (_UIApplicationConfigurationLoader.m:30)
11 UIKitCore 0x00000001ab108160 __63-[_UIApplicationConfigurationLoader _loadInitializationContext]_block_invoke + 100 (_UIApplicationConfigurationLoader.m:106)
12 libdispatch.dylib 0x00000001a8745db0 _dispatch_client_callout + 20 (object.m:559)
13 libdispatch.dylib 0x00000001a87475c8 _dispatch_once_callout + 32 (once.c:52)
14 UIKitCore 0x00000001ab1080f8 -[_UIApplicationConfigurationLoader _loadInitializationContext] + 152 (once.h:84)
15 UIKitCore 0x00000001ab108408 __70-[_UIApplicationConfigurationLoader startPreloadInitializationContext]_block_invoke + 28 (_UIApplicationConfigurationLoader.m:154)
16 libdispatch.dylib 0x00000001a874424c _dispatch_call_block_and_release + 32 (init.c:1454)
17 libdispatch.dylib 0x00000001a8745db0 _dispatch_client_callout + 20 (object.m:559)
18 libdispatch.dylib 0x00000001a8756a68 _dispatch_root_queue_drain + 656 (inline_internal.h:2548)
19 libdispatch.dylib 0x00000001a8757120 _dispatch_worker_thread2 + 116 (queue.c:6777)
20 libsystem_pthread.dylib 0x00000001f46017d8 _pthread_wqthread + 216 (pthread.c:2223)
21 libsystem_pthread.dylib 0x00000001f460876c start_wqthread + 8
Thread 4:
0 libsystem_pthread.dylib 0x00000001f4608764 start_wqthread + 0
Thread 5 name:
Thread 5 Crashed:
0 FrontBoardServices 0x00000001b88d13cc -[FBSSceneParameters initWithSpecification:] + 228 (FBSSceneParameters.m:34)
1 FrontBoardServices 0x00000001b88d1320 -[FBSSceneParameters initWithSpecification:] + 56 (FBSSceneParameters.m:34)
2 FrontBoardServices 0x00000001b88d1dd8 -[FBSSceneParameters initWithXPCDictionary:] + 128 (FBSSceneParameters.m:150)
3 BaseBoard 0x00000001ad165af4 _BSXPCDecodeObject + 1892 (BSXPCCoder.m:583)
4 BaseBoard 0x00000001ad1639c0 _BSXPCDecodeObjectForKey + 268 (BSXPCCoder.m:459)
5 BoardServices 0x00000001c2585f30 +[BSXPCServiceConnectionProxy decodeArguments:outArgs:fromMessage:forConnection:] + 1608 (BSXPCServiceConnectionProxy.m:592)
6 BoardServices 0x00000001c2583ab0 -[BSXPCServiceConnectionProxy invokeMessage:onTarget:] + 276 (BSXPCServiceConnectionProxy.m:342)
7 BoardServices 0x00000001c258a994 __63-[BSXPCServiceConnectionEventHandler connection:handleMessage:]_block_invoke + 536 (BSXPCServiceConnectionEventHandler.m:261)
8 BoardServices 0x00000001c25a0284 BSXPCServiceConnectionExecuteCallOut + 316 (BSXPCServiceConnection.m:1049)
9 BoardServices 0x00000001c258a708 -[BSXPCServiceConnectionEventHandler connection:handleMessage:] + 172 (BSXPCServiceConnectionEventHandler.m:250)
10 BoardServices 0x00000001c259f668 -[BSXPCServiceConnection _connection_handleMessage:fromPeer:withHandoff:] + 572 (BSXPCServiceConnection.m:834)
11 libdispatch.dylib 0x00000001a874424c _dispatch_call_block_and_release + 32 (init.c:1454)
12 libdispatch.dylib 0x00000001a8745db0 _dispatch_client_callout + 20 (object.m:559)
13 libdispatch.dylib 0x00000001a874d10c _dispatch_lane_serial_drain + 580 (inline_internal.h:2548)
14 libdispatch.dylib 0x00000001a874dc90 _dispatch_lane_invoke + 460 (queue.c:3862)
15 libdispatch.dylib 0x00000001a874cfd8 _dispatch_lane_serial_drain + 272 (inline_internal.h:2589)
16 libdispatch.dylib 0x00000001a874dc90 _dispatch_lane_invoke + 460 (queue.c:3862)
17 libdispatch.dylib 0x00000001a8757d78 _dispatch_workloop_worker_thread + 708 (queue.c:6601)
18 libsystem_pthread.dylib 0x00000001f4601814 _pthread_wqthread + 276 (pthread.c:2210)
19 libsystem_pthread.dylib 0x00000001f460876c start_wqthread + 8
Thread 6 name:
Thread 6:
0 libsystem_kernel.dylib 0x00000001d6a822d0 mach_msg_trap + 8
1 libsystem_kernel.dylib 0x00000001d6a81660 mach_msg + 76 (mach_msg.c:103)
2 IOKit 0x00000001b3b68340 io_hideventsystem_copy_property + 172 (IOHIDEventSystemMIGUser.c:3056)
3 IOKit 0x00000001b3b22c60 IOHIDEventSystemClientCopyProperty + 128 (IOHIDEventSystemClient.c:1097)
4 IOKit 0x00000001b3b22354 __IOHIDEventSystemClientRefresh + 1148 (IOHIDEventSystemClient.c:539)
5 IOKit 0x00000001b3b230cc IOHIDEventSystemClientCreateWithType + 856 (IOHIDEventSystemClient.c:749)
6 BackBoardServices 0x00000001ac0dda88 ___getHIDEventSystemClient_block_invoke + 288 (BKSHIDEvent.m:93)
7 libdispatch.dylib 0x00000001a8745db0 _dispatch_client_callout + 20 (object.m:559)
8 libdispatch.dylib 0x00000001a87475c8 _dispatch_once_callout + 32 (once.c:52)
9 BackBoardServices 0x00000001ac0dd964 BKSHIDEventRegisterEventCallbackOnRunLoop + 152 (once.h:84)
10 UIKitCore 0x00000001ab5babe4 -[UIEventFetcher threadMain] + 416 (UIEventFetcher.m:720)
11 Foundation 0x00000001a9ee7a34 __NSThread__start__ + 864 (NSThread.m:724)
12 libsystem_pthread.dylib 0x00000001f45ffcb0 _pthread_start + 320 (pthread.c:881)
13 libsystem_pthread.dylib 0x00000001f4608778 thread_start + 8
Thread 7:
0 libsystem_pthread.dylib 0x00000001f4608764 start_wqthread + 0
Thread 5 crashed with ARM Thread State (64-bit):
x0: 0x000000020ba16880 x1: 0x000000020ba16880 x2: 0x0000000000000000 x3: 0x00000000000008fd
x4: 0x0000000000000000 x5: 0x00000001bdb9873e x6: 0x000000000000006e x7: 0x0000000000000fb0
x8: 0x85f836c8121c001f x9: 0x85f836c8121c001f x10: 0x0000000000005403 x11: 0x0000000281a71540
x12: 0x00000000000000aa x13: 0x0000000000000001 x14: 0x00000000000000ac x15: 0x0000000000000182
x16: 0x00000002c6d90f88 x17: 0x0000000208ac3dc8 x18: 0x0000000000000000 x19: 0x0000000000000000
x20: 0x0000000281472eb0 x21: 0x0000000000000000 x22: 0x0000000000000000 x23: 0x00000001f75f31f5
x24: 0x000000020ba160d8 x25: 0x0000000000000000 x26: 0x00000001f7ff3288 x27: 0x000000020ba160b0
x28: 0x0000000000000000 fp: 0x000000016bb2e130 lr: 0x86106081b88d1320
sp: 0x000000016bb2e100 pc: 0x00000001b88d13cc cpsr: 0x60000000
esr: 0xf2000000 Address size fault
What could be causing the app to crash in a real car but work fine in the simulator? Here is part of my AppDelegate where I call a function to setup carplay:
import UIKit
import AVFoundation
import AVKit
import GoogleInteractiveMediaAds
import MediaPlayer
import GoogleMobileAds
import UserNotifications
import WebKit
import SafariServices
import Hero
import Firebase
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
static let reachable = "Reachable"
static let unReachable = "UnReachable"
let reachability = try! Reachability()
var iOSStream: String?
var preRolladUrl: String?
var window: UIWindow?
var adType: String?
var adServer: String?
var adFeed: String?
var miniPlayer: PlayerPopupControlViewController?
var selectedStation: Players!
// CarPlay
var playableContentManager: MPPlayableContentManager?
let carplayPlaylist = CarPlayPlaylist()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UINavigationBar.appearance().barTintColor = UIColor.black
UINavigationBar.appearance().tintColor = UIColor.black
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
UINavigationBar.appearance().isTranslucent = false
if UserDefaults.standard.object(forKey: UserDefaultsConstants.resumeRadioInBackground) == nil {
UserDefaults.standard.set(true, forKey: UserDefaultsConstants.resumeRadioInBackground)
UserDefaults.standard.synchronize()
}
self.setupBaseURL()
// Override point for customization after application launch.
self.startObservingReachability()
UIApplication.shared.beginReceivingRemoteControlEvents()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
AppLogger.error(error)
}
UNUserNotificationCenter.current().delegate = self
UserDefaults.standard.set(false, forKey: UserDefaultsConstants.isMiniPlayerDisplayed)
UserDefaults.standard.synchronize()
SettingsDataManager.sharedInstance.selectedStation = SettingsDataManager.sharedInstance.getSelectedStationFromUserDefaults()
registerForPushNotifications()
setupCarPlay()
FirebaseApp.configure()
return true
}
AppDelegate+CarPlay.swift
import Foundation
import MediaPlayer
extension AppDelegate{
func setupCarPlay() {
playableContentManager = MPPlayableContentManager.shared()
playableContentManager?.delegate = self
playableContentManager?.dataSource = self
self.carplayPlaylist.setupCommandCenter()
}
}
extension AppDelegate: MPPlayableContentDelegate {
// This is called when user selects a 'playable' item (MPContentItem)
func playableContentManager(_ contentManager: MPPlayableContentManager, initiatePlaybackOfContentItemAt indexPath: IndexPath, completionHandler: #escaping (Error?) -> Void) {
self.carplayPlaylist.playerData = SettingsDataManager.sharedInstance.playerData ?? []
// guard let miniPlayer = self.miniPlayer else {return}
DispatchQueue.main.async {
// App should play music either from the radio stream or podcasts
if indexPath.count == 2 {
if(indexPath[0] == 0) {
// When user selects playable item within Radio tab
if (self.carplayPlaylist.playerData.count > 0) {
if let stationURL = URL(string: self.carplayPlaylist.playerData[indexPath[1]].streams?.iOS ?? "") {
self.carplayPlaylist.play(playURL: stationURL)
SettingsDataManager.sharedInstance.selectedStation = self.carplayPlaylist.playerData[indexPath[1]]
}
}
}
}
completionHandler(nil)
// Workaround to make the Now Playing working on the simulator:
#if targetEnvironment(simulator)
UIApplication.shared.endReceivingRemoteControlEvents()
UIApplication.shared.beginReceivingRemoteControlEvents()
#endif
}
}
func beginLoadingChildItems(at indexPath: IndexPath, completionHandler: #escaping (Error?) -> Void) {
carplayPlaylist.load { error in
completionHandler(error)
}
}
}
extension AppDelegate: MPPlayableContentDataSource {
func numberOfChildItems(at indexPath: IndexPath) -> Int {
if indexPath.indices.count == 0 {
// This returns the number of tabs at the top of the CarPlay display
return 1 // changed to 1 to allow only radio streams
} else if indexPath.indices.count == 1 {
// This returns the number of rows within each tab
if indexPath[0] == 0 {
// Radio Stations rows
return carplayPlaylist.playerData.count
} else {
// Podcasts feed rows
return 0 // Return 0 while podcasts are disabled
}
} else {
return 0
}
}
func contentItem(at indexPath: IndexPath) -> MPContentItem? {
let playerData = carplayPlaylist.playerData
// let podCastsFeeds = carplayPlaylist.podCastSettings?.podcasts_feeds
if indexPath.count == 1 {
// Tab section
let item: MPContentItem
if (indexPath[0] == 0) {
// Radio Stations Tab Section
item = MPContentItem(identifier: "Radio")
item.title = "Radio"
item.artwork = MPMediaItemArtwork(boundsSize: #imageLiteral(resourceName: "NavIcon-Broadcast").size, requestHandler: { _ -> UIImage in
return #imageLiteral(resourceName: "NavIcon-Broadcast")
})
} else {
// Podcast Tab Section
item = MPContentItem(identifier: "Podcasts")
item.title = "Podcasts"
item.artwork = MPMediaItemArtwork(boundsSize: #imageLiteral(resourceName: "NavIcon-Podcasts").size, requestHandler: { _ -> UIImage in
return #imageLiteral(resourceName: "NavIcon-Podcasts")
})
}
item.isContainer = true
item.isPlayable = false
return item
} else if indexPath.count == 2, indexPath.item < playerData.count, indexPath[0] == 0 {
// Radio station items section
let station = playerData[indexPath.item]
let item = MPContentItem(identifier: "\(station.name)")
item.title = station.name
item.subtitle = station.call_letters
item.isPlayable = true
item.isStreamingContent = true
item.downloadImageAndSetArtwork(from: station.logo ?? "", completion: {})
return item
} else {
return nil
}
}
}
///extension to downlaod the image from the api
extension MPContentItem {
func getData(from url: URL, completion: #escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
func downloadImageAndSetArtwork(from address: String, completion: #escaping () -> Void) {
let defaultImage = #imageLiteral(resourceName: "NavIcon-Music")
let defaultArtwork = MPMediaItemArtwork(boundsSize: defaultImage.size, requestHandler: { _ -> UIImage in
return defaultImage
})
guard let url = URL(string: address) else {
self.artwork = defaultArtwork
return
}
getData(from: url) {
data, response, error in
guard let data = data, error == nil else {
AppLogger.error("Image Error")
self.artwork = defaultArtwork
return
}
DispatchQueue.main.async() {
guard let image = UIImage(data: data) else {
self.artwork = defaultArtwork
return
}
self.artwork = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { _ -> UIImage in
return image
})
completion()
}
}
}
}
CarPlayPlaylist.swift
import Foundation
//import UIKit
import AVKit
import MediaPlayer
class CarPlayPlaylist {
let radioPlayer = FRadioPlayer.shared
var playerData: [Players] = []
var podCastItemsArray: [[Item]] = []
var podCastSettings: Podcast_settings?
var podCastFeedNameArray:[String] = []
var isFromCarPlay: Bool = false
var playButtonStatus: Bool = false
var currentPodcastItem: Item?
func load(_ completion: #escaping (Error?) -> Void) {
// if (self.podCastFeedNameArray.count == 0 && self.podCastItemsArray.count == 0) {
// getPodcastDataFromSettingsDataManager()
//
// let podcastFeedsCount = self.podCastSettings?.podcasts_feeds?.count ?? 0
// podCastItemsArray = [[Item]](repeating: [], count: podcastFeedsCount)
// }
self.playerData = SettingsDataManager.sharedInstance.playerData ?? []
completion(nil)
}
func play (playURL: URL) {
isFromCarPlay = true
self.radioPlayer.radioURL = playURL
self.radioPlayer.play()
}
func setupCommandCenter () {
MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyTitle: "Current Playing song"]
MPNowPlayingInfoCenter.default().nowPlayingInfo![MPNowPlayingInfoPropertyPlaybackRate] = 0.0
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.isEnabled = true
commandCenter.pauseCommand.isEnabled = true
commandCenter.playCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
self?.radioPlayer.play()
// NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationCenterConstants.carPlayDidPlay), object: nil, userInfo: nil)
return .success
}
commandCenter.pauseCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
self?.radioPlayer.pause()
// NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationCenterConstants.carPlayDidPause), object: nil, userInfo: nil)
return .success
}
}
}
extension CarPlayPlaylist {
func addCommandCenterNotificationObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(commandCenterDidPlay), name: NSNotification.Name(rawValue: NotificationCenterConstants.commandCenterDidPlay), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(commandCenterDidPause), name: NSNotification.Name(rawValue: NotificationCenterConstants.commandCenterDidPause), object: nil)
}
func removeCommandCenterObservers() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NotificationCenterConstants.commandCenterDidPlay), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NotificationCenterConstants.commandCenterDidPause), object: nil)
}
#objc func commandCenterDidPlay() {
// Playback rate should change the playback status
MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyPlaybackRate] = 0.0
}
#objc func commandCenterDidPause() {
// Playback rate should change the playback status
MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyPlaybackRate] = 1.0
}
}

XCode Crash Report (Already Symbolicated) Missing Line Numbers

I have a crash report (it is already symbolicated at least I would hope so as I obtained this log from XCode Organizer)
Incident Identifier: F4324555-0916-4E32-82EF-3272917367BB
Beta Identifier: 80811904-A512-48A1-9593-D386703A62F0
Hardware Model: iPhone7,2
Process: SelfieSuperStarz [596]
Path: /private/var/containers/Bundle/Application/BFA0D82B-274B-400B-8F84-52A1D7369C51/SelfieSuperStarz.app/SelfieSuperStarz
Identifier: com.PuckerUp.PuckerUp
Version: 21 (1.31)
Beta: YES
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
Coalition: com.PuckerUp.PuckerUp [434]
Date/Time: 2017-07-29 20:06:11.7394 -0400
Launch Time: 2017-07-29 19:34:39.7433 -0400
OS Version: iPhone OS 10.3.2 (14F89)
Report Version: 104
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Triggered by Thread: 0
Last Exception Backtrace:
0 CoreFoundation 0x18bebafe0 __exceptionPreprocess + 124 (NSException.m:165)
1 libobjc.A.dylib 0x18a91c538 objc_exception_throw + 56 (objc-exception.mm:521)
2 CoreFoundation 0x18be26eb4 -[__NSArray0 objectAtIndex:] + 108 (CFArray.c:69)
3 SelfieSuperStarz 0x10007b708 specialized _ArrayBuffer._getElementSlowPath(Int) -> AnyObject + 116
4 SelfieSuperStarz 0x10007ea40 specialized Merger.merge(completion : () -> (), assets : [Asset]) -> () + 1444 (Merger.swift:0)
5 SelfieSuperStarz 0x100071f3c specialized AssetView.finish(UIButton) -> () + 520 (Merger.swift:0)
6 SelfieSuperStarz 0x1000712d0 #objc AssetView.finish(UIButton) -> () + 40 (AssetView.swift:0)
7 UIKit 0x192021010 -[UIApplication sendAction:to:from:forEvent:] + 96 (UIApplication.m:4580)
8 UIKit 0x192020f90 -[UIControl sendAction:to:forEvent:] + 80 (UIControl.m:609)
9 UIKit 0x19200b504 -[UIControl _sendActionsForEvents:withEvent:] + 440 (UIControl.m:694)
10 UIKit 0x192020874 -[UIControl touchesEnded:withEvent:] + 576 (UIControl.m:446)
11 UIKit 0x192020390 -[UIWindow _sendTouchesForEvent:] + 2480 (UIWindow.m:2122)
12 UIKit 0x19201b728 -[UIWindow sendEvent:] + 3192 (UIWindow.m:2292)
13 UIKit 0x191fec33c -[UIApplication sendEvent:] + 340 (UIApplication.m:10778)
14 UIKit 0x1927e6014 __dispatchPreprocessedEventFromEventQueue + 2400 (UIEventDispatcher.m:1448)
15 UIKit 0x1927e0770 __handleEventQueue + 4268 (UIEventDispatcher.m:1671)
16 UIKit 0x1927e0b9c __handleHIDEventFetcherDrain + 148 (UIEventDispatcher.m:1706)
17 CoreFoundation 0x18be6942c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24 (CFRunLoop.c:1943)
18 CoreFoundation 0x18be68d9c __CFRunLoopDoSources0 + 540 (CFRunLoop.c:1989)
19 CoreFoundation 0x18be669a8 __CFRunLoopRun + 744 (CFRunLoop.c:2821)
20 CoreFoundation 0x18bd96da4 CFRunLoopRunSpecific + 424 (CFRunLoop.c:3113)
21 GraphicsServices 0x18d800074 GSEventRunModal + 100 (GSEvent.c:2245)
22 UIKit 0x192051058 UIApplicationMain + 208 (UIApplication.m:4089)
23 SelfieSuperStarz 0x10002e990 main + 56 (AppDelegate.swift:16)
24 libdyld.dylib 0x18ada559c start + 4
As you can see it says in my Class Merger at line 0. Which is impossible, as you can probably assume. I am not sure how to interpret what specialized means or why the #objc is there.
3 SelfieSuperStarz 0x10007b708 specialized _ArrayBuffer._getElementSlowPath(Int) -> AnyObject + 116
4 SelfieSuperStarz 0x10007ea40 specialized Merger.merge(completion : () -> (), assets : [Asset]) -> () + 1444 (Merger.swift:0)
5 SelfieSuperStarz 0x100071f3c specialized AssetView.finish(UIButton) -> () + 520 (Merger.swift:0)
6 SelfieSuperStarz 0x1000712d0 #objc AssetView.finish(UIButton) -> () + 40 (AssetView.swift:0)
Just not sure where the error is occurring as the line says Merger:0 and I'm not sure what those headers (specialized/objc) mean if they are telling me anything.
Here is my merge function inside Merger. I use a variety of loops and calculations for opacity and determine things, but I check for nil in locations.
func merge(completion:#escaping () -> Void, assets:[Asset]) {
self.setupAI()
let assets = assets.sorted(by: { $0.layer.zPosition < $1.layer.zPosition })
if let firstAsset = controller.firstAsset {
let mixComposition = AVMutableComposition()
let firstTrack = mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo,
preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
do {
try firstTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, self.controller.realDuration),
of: firstAsset.tracks(withMediaType: AVMediaTypeVideo)[0],
at: kCMTimeZero)
} catch _ {
print("Failed to load first track")
}
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
var myTracks:[AVMutableCompositionTrack] = []
var ranges:[ClosedRange<CMTime>] = []
for asset in assets {
let secondTrack = mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo,
preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
secondTrack.preferredTransform = asset.asset.preferredTransform
do {
try secondTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, asset.endTime-asset.beginTime),
of: asset.asset.tracks(withMediaType: AVMediaTypeVideo)[0],
at: CMTime(seconds: CMTimeGetSeconds(asset.beginTime), preferredTimescale: 600000))
} catch _ {
print("Failed to load second track")
}
if(ranges.count == 0) {
ranges.append(asset.beginTime...asset.endTime)
}
else {
var none = true
for range in ranges {
let start = range.contains(asset.beginTime)
let end = range.contains(asset.endTime)
var connection = false
var nothing = false
//This range is completely encompassed (begin and end inside)
if(start && end) {
//Don't add to the rnge
none = false
nothing = true
}
//Begin is in range (right side)
else if(start && !end) {
connection = true
none = false
}
//End is in range (left side)
else if(!start && end) {
connection = true
none = false
}
var connected = false
//It connects 2 different timess
if(connection) {
for range2 in ranges {
if(range != range2) {
if(start && range2.contains(asset.endTime)) {
let index = ranges.index(of: range)
if(index != nil) {
ranges.remove(at: index!)
ranges.append(range.lowerBound...range2.upperBound)
connected = true
break
}
}
else if(end && range2.contains(asset.beginTime)) {
let index = ranges.index(of: range)
if(index != nil) {
ranges.remove(at: index!)
ranges.append(range.lowerBound...range2.upperBound)
connected = true
break
}
}
}
}
}
if(!connected && !none && !nothing) {
if(start) {
let index = ranges.index(of: range)
if(index != nil) {
ranges.remove(at: index!)
ranges.append(range.lowerBound...asset.endTime)
}
}
else if(end) {
let index = ranges.index(of: range)
if(index != nil) {
ranges.remove(at: index!)
ranges.append(asset.beginTime...asset.endTime)
}
}
}
}
if(none) {
ranges.append(asset.beginTime...asset.endTime)
}
}
myTracks.append(secondTrack)
}
for range in ranges {
print(CMTimeGetSeconds(range.lowerBound), CMTimeGetSeconds(range.upperBound))
}
for assets in self.controller.assets {
print(CMTimeGetSeconds(assets.beginTime), CMTimeGetSeconds(assets.endTime))
}
if let loadedAudioAsset = self.controller.audioAsset {
let audioTrack = mixComposition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: 0)
do {
try audioTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, self.controller.realDuration),
of: loadedAudioAsset.tracks(withMediaType: AVMediaTypeAudio)[0] ,
at: kCMTimeZero)
} catch _ {
print("Failed to load Audio track")
}
}
let mainInstruction = AVMutableVideoCompositionInstruction()
mainInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, self.controller.realDuration)
// 2.2
let firstInstruction = self.videoCompositionInstructionForTrack(firstTrack, firstAsset)
var instructions:[AVMutableVideoCompositionLayerInstruction] = []
var counter:Int = 0
for tracks in myTracks {
let secondInstruction = self.videoCompositionInstructionForTrack(tracks, assets[counter].asset, type:true)
let index = myTracks.index(of: tracks)
//This should never be nil, but if it is, it might cause opacity's to go out of whack for that specific track. Only reason I can think of why I am crashing in this method.
if(index != nil) {
if(index! < assets.count-1) {
for i in (counter+1...assets.count-1) {
if(assets[counter].endTime > assets[i].endTime) {
secondInstruction.setOpacity(1.0, at: assets[i].endTime)
secondInstruction.setOpacity(0.0, at: assets[counter].endTime)
print("Bigger")
break
}
}
}
if(index! > 0) {
for i in (0...counter).reversed() {
if(assets[counter].endTime < assets[i].endTime) {
secondInstruction.setOpacity(0.0, at: assets[counter].endTime)
print("Smaller")
break
}
}
}
if(counter < myTracks.count-1) {
if(assets[counter].layer.zPosition <= assets[counter+1].layer.zPosition) {
secondInstruction.setOpacity(0.0, at: assets[counter+1].beginTime)
}
else {
secondInstruction.setOpacity(0.0, at: assets[counter].endTime)
}
}
instructions.append(secondInstruction)
counter += 1
}
}
for range in ranges {
firstInstruction.setOpacity(0.0, at: range.lowerBound)
firstInstruction.setOpacity(1.0, at: range.upperBound)
}
// 2.3
mainInstruction.layerInstructions = [firstInstruction] + instructions
let imageLayer = CALayer()
let image = UIImage(named: "Watermark")
imageLayer.contents = image!.cgImage
let ratio = (firstAsset.tracks(withMediaType: AVMediaTypeVideo)[0].naturalSize.width/image!.size.width)/2
let rect = CGRect(x: image!.size.width*ratio, y: 0, width: image!.size.width*ratio, height: image!.size.height*ratio)
imageLayer.frame = rect
imageLayer.backgroundColor = UIColor.clear.cgColor
imageLayer.opacity = 0.75
let videoLayer = CALayer()
videoLayer.frame = CGRect(x: 0, y: 0, width: firstAsset.tracks(withMediaType: AVMediaTypeVideo)[0].naturalSize.width, height: firstAsset.tracks(withMediaType: AVMediaTypeVideo)[0].naturalSize.height)
let parentlayer = CALayer()
parentlayer.frame = CGRect(x: 0, y: 0, width: image!.size.width*ratio, height: image!.size.height*ratio)
parentlayer.addSublayer(videoLayer)
parentlayer.addSublayer(imageLayer)
let mainComposition = AVMutableVideoComposition()
mainComposition.instructions = [mainInstruction]
mainComposition.frameDuration = CMTimeMake(1, 30)
mainComposition.renderSize = self.controller.firstAsset!.tracks(withMediaType: AVMediaTypeVideo)[0].naturalSize
mainComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentlayer)
It's quite clear that the method "Merger.merge" accesses a non-existing element. The debugger will show you where that is.
I'd guess that some thread is modifying some array behind your back so that an index that was valid at some point becomes invalid. And "for range2 in ranges" when you later on modify "ranges" is asking for trouble.
I am guessing that the problem is caused by line 129, considering the +1444 offset and array access. Have you tried a video without audio, like a video taken without an audio permission? I encountered an out of bound crash by assuming videos taken in my app always had audio tracks. You will be surprised by users what video they feed into your app. I even had a user crashing my app with a flv video, selected from their phone album.
(I am not sure if this will work for Swift)
It is also possible to locate the line in Xcode using the debugger. First, you run the app with the same optimzation setting as the release build. Then you break different lines in the function to check the assembly code.
How to see assembly code in xcode 6. You might need to scroll to the top to double check the function name and the meaning of the offset.
_ArrayBuffer._getElementSlowPath is a class in the private API, indicated by the underscore prefix. You will probably not find any credible and/or official sources about it.
The incompleteness in your crash log is probably caused by bugs/immaturity of Swift (the tools behind it). Welcome to one of the most trended and hyped language. Even in working conditions, Swift gives line 0 for generated code where the code does not correspond to any meaningful parts of the source code. It is not your case though.

Serious Application Core Data Error Swift3

I am trying to get data from multiple apis and saving it to my coredata database. Earlier it comes once in ten times. but now i am getting it every time.
I have created a DispatchGroup and trying to hit api one by one. Below is my code.
let group = DispatchGroup()
group.enter()
SharedFunctions.getCourseSessions {
print("Course Session Done")
group.leave()
}
group.enter()
SharedFunctions.getCourseContent {
print("Course Content Done")
group.leave()
}
group.enter()
SharedFunctions.getCourseQuiz {
print("Course Quiz Done")
group.leave()
}
group.notify(queue: DispatchQueue.global(qos: .background)) {
print("All async calls were run!")
DispatchQueue.main.async {
ACProgressHUD.shared.hideHUD()
completrion()
}
}
Below is my fetching and saving data from api
class func getCourseSessions(completion: #escaping () -> ()) {
let param = "module=getCourseSessions&userid=\(User.uId)&Akey=\(User.akey)&schedule_course_id=\(User.scheduleCourseId)"
SharedFunctions.callWebServices(url: URLS.Base_URL, methodName: "POST", parameters: param, istoken: false, tokenval: "", completion: { (jsonDict) in
print(jsonDict)
DispatchQueue.main.async {
if ((jsonDict.value(forKey: "message") as! NSDictionary).value(forKey: "success") as! String) == "true" {
SharedGlobalVariables.arrayCourseSessions = (((jsonDict.value(forKey: "message") as AnyObject).value(forKey: "data") as AnyObject).value(forKey: "result")) as! NSMutableArray
print(SharedGlobalVariables.arrayCourseSessions.count)
// DispatchQueue.main.async {
SharedGlobalVariables.LoginBool = true
// get a reference to the app delegate
if #available(iOS 10.0, *) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
print(SharedGlobalVariables.arrayCourseSessions.count)
for j in 0...SharedGlobalVariables.arrayCourseSessions.count - 1 {
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Course_Sessions", in: managedContext)
let courseSessionsScreen = Course_Sessions(entity: entity!, insertInto: managedContext)
if let arrData = SharedGlobalVariables.arrayCourseSessions[j] as? NSDictionary {
if let courseId = arrData.value(forKey: "course_id") as? Int16 {
courseSessionsScreen.course_id = courseId
}
if let userId = arrData.value(forKey: "user_id") as? Int16 {
courseSessionsScreen.user_id = userId
}
if let enableNextScreenSequence = arrData.value(forKey: "enable_nextscreen_sequence") as? Int16 {
courseSessionsScreen.enable_nextscreen_sequence = enableNextScreenSequence
}
}
do {
try managedContext.save()
// getCourseSessionProperties()
} catch let error as NSError {
print(error)
}
}
} else {
// Fallback on earlier versions
}
//}
}
completion()
}
})
}
There is no perticular place to crash app crash. it crash any where like above methode i am passing all apis.
Getting This error:
Error Domain=NSCocoaErrorDomain Code=132001 "(null)" UserInfo={message=attempt to recursively call -save: on the context aborted, stack trace=(
0 CoreData 0x0000000111ff3892 -[NSManagedObjectContext save:] + 306
1 Tuneem 0x000000010f64046c _TFFFZFC6Tuneem15SharedFunctions26getCourseSessionPropertiesFT10completionFT_T__T_U_FCSo12NSDictionaryT_U_FT_T_U_FT_T_ + 60
2 Tuneem 0x000000010f629197 _TTRXFo___XFdCb___ + 39
3 CoreData 0x000000011200cb52 developerSubmittedBlockToNSManagedObjectContextPerform + 178
4 libdispatch.dylib 0x000000011bf0205c _dispatch_client_callout + 8
5 libdispatch.dylib 0x000000011bee094f _dispatch_queue_serial_drain + 221
6 libdispatch.dylib 0x000000011bee1669 _dispatch_queue_invoke + 1084
7 libdispatch.dylib 0x000000011bee1b32 _dispatch_queue_override_invoke + 654
8 libdispatch.dylib 0x000000011bee3ec4 _dispatch_root_queue_drain + 634
9 libdispatch.dylib 0x000000011bee3bef _dispatch_worker_thread3 + 123
10 libsystem_pthread.dylib 0x000000011c299712 _pthread_wqthread + 1299
11 libsystem_pthread.dylib 0x000000011c2991ed start_wqthread + 13
)}
Error Domain=NSCocoaErrorDomain Code=132001 "(null)" UserInfo=. {message=attempt to recursively call -save: on the context aborted, stack trace=(
0 CoreData 0x0000000111ff3892 -[NSManagedObjectContext save:] + 306
1 Tuneem 0x000000010f64046c _TFFFZFC6Tuneem15SharedFunctions26getCourseSessionPropertiesFT10completionFT_T__T_U_FCSo12NSDictionaryT_U_FT_T_U_FT_T_ + 60
2 Tuneem 0x000000010f629197 _TTRXFo___XFdCb___ + 39
3 CoreData 0x000000011200cb52 developerSubmittedBlockToNSManagedObjectContextPerform + 178
4 libdispatch.dylib 0x000000011bf0205c _dispatch_client_callout + 8
5 libdispatch.dylib 0x000000011bee094f _dispatch_queue_serial_drain + 221
6 libdispatch.dylib 0x000000011bee1669 _dispatch_queue_invoke + 1084
7 libdispatch.dylib 0x000000011bee1b32 _dispatch_queue_override_invoke + 654
8 libdispatch.dylib 0x000000011bee3ec4 _dispatch_root_queue_drain + 634
9 libdispatch.dylib 0x000000011bee3bef _dispatch_worker_thread3 + 123
10 libsystem_pthread.dylib 0x000000011c299712 _pthread_wqthread + 1299
11 libsystem_pthread.dylib 0x000000011c2991ed start_wqthread + 13
)}
Trying to solve it from last couple of days getting no idea, any help will be appreciate.

Resources