When delegate is call, is crash with: EXC_BAD_ACCESS KERN_INVALID_ADDRESS
I can't understand what caused it..
func updateAnnotationLocation(_ annotation:Annotation,isNewAction:Bool){
self.updateAnnotationOnView(annotation)
if annotation.type == .Note {
(annotation as! NoteAnnotation).updateTextViewFrame()
}
var index = 0
while index<self.annotations.count {
if annotation.id == self.annotations[index].id {
if isNewAction {
let action = AnnotationAction(type: AnnotationActionType.UpdateAnnotationLocation, annotationBeforeAction: self.annotations[index],annotationAfterAction: annotation)
self.addActionToActionsList(action)
}
self.annotations[index] = annotation
if let selectedAnnotation = self.selectedAnnotation {
if annotation.id == selectedAnnotation.id {
self.selectedAnnotation = annotation
}
}
break
}
index += 1
}
}
Crash on:
if annotation.id == self.annotations[index].id
stack trace:
#0 Crashed: com.apple.main-thread EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000020
0 libobjc.A.dylib objc_retain + 16
1 FielNoteAnnotation.swift line 0 initializeWithCopy for NoteAnnotation
2 AnnotationViewController.swift line 746 AnnotationsViewController.updateAnnotationLocation(_:isNewAction:)
3 AnnotationViewController.swift line 915 AnnotationsViewController.undo()
4 AnnotationViewController.swift line 513 AnnotationsViewController.undo(_:)
5 AnnotationViewController.swift line 0 #objc AnnotationsViewController.undo(_:)
Related
I've been receiving a crash report from crashlytics-
Fatal Exception: NSInternalInconsistencyException 0 CoreFoundation
0x9e48 __exceptionPreprocess 1 libobjc.A.dylib 0x178d8
objc_exception_throw 2 Foundation 0x54594c
_userInfoForFileAndLine 3 UIKitCore 0x310db4 -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:]
4 UIKitCore 0x2703c8 -[UICollectionView
_performBatchUpdates:completion:invalidationContext:tentativelyForReordering:animator:animationHandler:]
5 0xd1a0dc
I am sharing a piece of code responsible for the crash, Although my collectionview have a huge code
collectionView.performBatchUpdates({
self.marketBatchUpdates(selectedOrderType: selectedOrderType)
}, completion: nil)
private func marketBatchUpdates(selectedOrderType: BrokerageTradingOrderTypeV2) {
let wasShowingSubmitButton = self.shouldShowSubmitButton()
if selectedOrderType != .Market {
if selectedOrderType == .Stop {
self.selectedOrderType = .Market
if self.showStopDisclosure == true {
collectionView.deleteItems(at: stopOrderDisclosureIndexPaths())
}
}
self.selectedOrderType = .Market
if selectedOrderType == .Limit || selectedOrderType == .StopLimit {
if self.selectedTerm == .DAY || self.selectedTerm == .GTC || self.selectedTerm == .SELECT {
collectionView.deleteItems(at: qualifierIndexPaths())
}
}
self.selectedTerm = .DAY
collectionView.reloadItems(at: termIndexPaths())
}
self.selectedOrderType = .Market
collectionView.reloadItems(at: orderTypeIndexPaths())
self.showOrderTypeSelections = false
collectionView.deleteItems(at: selectionsIndexPaths())
self.updateSubmitButton(previousSubmitButtonState: wasShowingSubmitButton)
}
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)
So this may be because UserDefaults are getting reset after a period of time, maybe because I update the OS frequently, but a released version of my iOS app after a period of time will crash on my login screen, probably where I check for saved credentials (in UserDefaults). Reinstalling the app fixes the issue. Console returns a lot of :
Unsupported use of UIKit view-customization API off the main thread. -setAlignsToKeyboard: sent to <_UIAlertControllerView: 0x125b2d070; frame = (0 0; 414 896); layer = <CALayer: 0x283f652e0>>
And my system logs show an error on this thread:
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Triggered by Thread: 4
Application Specific Information:
abort() called
Thread 4 name: Dispatch queue: com.apple.NSURLSession-delegate Thread
4 Crashed: 0 libsystem_kernel.dylib 0x00000001bfb4e414 0x1bfb26000 +
164884 1 libsystem_pthread.dylib 0x00000001dd6a8b50 0x1dd6a6000 +
11088 2 libsystem_c.dylib 0x000000019b027b74 0x19afb1000 + 486260 3
libc++abi.dylib 0x00000001a6d1acf8 0x1a6d07000 + 81144 4
libc++abi.dylib 0x00000001a6d0be4c 0x1a6d07000 + 20044 5
libobjc.A.dylib 0x00000001a6c14f64 0x1a6c0e000 + 28516 6
libc++abi.dylib 0x00000001a6d1a0e0 0x1a6d07000 + 78048 7
libc++abi.dylib 0x00000001a6d1a06c 0x1a6d07000 + 77932 8
libdispatch.dylib 0x00000001917eddc4 0x1917ea000 + 15812 9
libdispatch.dylib 0x00000001917f510c 0x1917ea000 + 45324 10
libdispatch.dylib 0x00000001917f5c90 0x1917ea000 + 48272 11
libdispatch.dylib 0x00000001917ffd78 0x1917ea000 + 89464 12
libsystem_pthread.dylib 0x00000001dd6a9814 0x1dd6a6000 + 14356 13
libsystem_pthread.dylib 0x00000001dd6b076c 0x1dd6a6000 + 42860
Here is some code that I use to check saved credentials. In the backend API I cannot see any login attempts. If it helps, I can see this viewcontroller for a split second right before it crashes. Not sure if that rules out viewdidload.
override func viewDidLoad() {
super.viewDidLoad()
addLoadingSpinner()
bLogIn.titleLabel?.font = UIFont.setToVoiceLight()
self.tfCustomerID.delegate = self
self.tfUsername.delegate = self
self.tfPassword.delegate = self
tfUsername.keyboardType = .default
tfPassword.textContentType = .password
setupUI()
if UserDefaults.standard.string(forKey: UserDefaultsKeys.session) != nil
&& UserDefaults.standard.string(forKey: UserDefaultsKeys.savedCred) == "True" {
login_session = UserDefaults.standard.string(forKey: UserDefaultsKeys.session)!
check_session()
}
else if UserDefaults.standard.string(forKey: UserDefaultsKeys.savedCred) == "True" &&
UserDefaults.standard.string(forKey: UserDefaultsKeys.usesBiometrics) == "True" {
promptTouchOrFaceID()
}
removeLoadingSpinner()
}
override func viewWillAppear(_ animated: Bool) {
AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.portrait, andRotateTo:
UIInterfaceOrientation.portrait)
cbSave.isChecked = UserDefaults.standard.string(forKey: UserDefaultsKeys.savedCred) == "True"
addObservers()
}
func check_session() {
UserDefaults.standard.set(login_session, forKey: "session")
UserInfo.access_token = UserDefaults.standard.string(forKey: "session")!
var request = URLRequest(url: NSURL(string: checksession_url)! as URL)
request.httpMethod = .GET
request.addValues(...)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
//VERIFIED THAT NEVER GETTING TO API
DispatchQueue.main.async {
...
}
} else {
self.promptTouchOrFaceID()
UserDefaults.standard.set(nil, forKey: UserDefaultsKeys.session)
}
}
task.resume()
}
Here is my code for biometrics prompt:
func promptTouchOrFaceID() {
//create context for touch auth
let authenticationContext = LAContext()
var error: NSError?
authenticationContext.localizedFallbackTitle = ""
let biometricType = authenticationContext.biometricType
//check if the device has a fingerprint sensor, exit if not
guard authenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
error: &error) else {
let title = "Error"
var message = ""
switch biometricType {
case .faceID:
message = "This device does not have a FaceID sensor or the sensor is not enabled."
case .touchID:
message = "This device does not have a TouchID sensor or the sensor is not enabled."
case .none:
message = "This device does not have any sensors to use TouchID or FaceID"
}
AlertService.showAlert(on: self, title: title, message: message)
UserDefaults.standard.set("False", forKey: UserDefaultsKeys.usesBiometrics)
removeLoadingSpinner()
return
}
authenticationContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
localizedReason: "Please use your fingerprint to authenticate.",
reply: { [unowned self] (success, error) -> Void in
if (success) {
//fingerprint recognized, set this possible and go to view controller
OperationQueue.main.addOperation({ () -> Void in
self.fillInUserDetails()
self.login_now(
username:self.tfUsername.text!,
password: self.userDefaults.string(forKey: UserDefaultsKeys.password)!,
customer: self.tfCustomerID.text!)
})
}
})
}
Just a wild shot, but do you have NSFaceIDUsageDescription key in your plist file. I remember having a problem like this a few months back.
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
}
}
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.