iOS App Store app crashes during login (not in development) - ios

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.

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()
}
)}
}

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

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)

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.

Crashed: com.apple.main-thread EXC_BREAKPOINT 0x0000000100c5009c keyboard_arrow_up

I am new iOS development, I got this error from firebase crash analytics. Can anyone help me why this errors occurs?
Crashed: com.apple.main-thread
0 People Time Tracking 0x100c5009c closure #1 in closure #1 in SelectJobScreen.getPreviousStatus() (SelectJobScreen.swift:798)
1 People Time Tracking 0x100cb2648 thunk for #escaping #callee_guaranteed () -> () (<compiler-generated>)
2 libdispatch.dylib 0x1e6993a38 _dispatch_call_block_and_release + 24
3 libdispatch.dylib 0x1e69947d4 _dispatch_client_callout + 16
4 libdispatch.dylib 0x1e6942004 _dispatch_main_queue_callback_4CF$VARIANT$mp + 1068
5 CoreFoundation 0x1e6ee4ec0 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
6 CoreFoundation 0x1e6edfdf8 __CFRunLoopRun + 1924
7 CoreFoundation 0x1e6edf354 CFRunLoopRunSpecific + 436
8 GraphicsServices 0x1e90df79c GSEventRunModal + 104
9 UIKitCore 0x212cc5b68 UIApplicationMain + 212
10 People Time Tracking 0x100c1afcc main (TodoItem.swift:17)
11 libdyld.dylib 0x1e69a58e0 start + 4
I've tried figuring out what could cause this crash for a few days now, and haven't been able to reproduce it. I don't see any implicit unwraps or optionals here, but sessionId is a non-optional value in the session object if that matters.
I am using swift 4.1, and the crashes occur on on iOS devices running all the different flavours of iOS 10, 11, and 12. The app does support some builds of iOS 9, but none have been reported (although that may be irrelevant because the iOS 9 user base for the app is extremely small)
In Error log it's showing this function getPreviousStatus()
func getPreviousStatus() {
let connect = JsonManger()
let app = UIApplication.shared.delegate as! AppDelegate
let user:User = app.dataManager.gUser
if Reachability.isConnectedToNetwork() {
self.showHUD( msg: "Loading...." )
connect.getLogDetails(baseUrl: user.ClientWeb, email: user.EmailID, password: user.Password, brugerId: user.BrugerID, success: { (res) in
var indud = false
if ( res.object(forKey: "indud") != nil ){
indud = res.object(forKey: "indud") as! Bool
}
if indud {
var isTodo = false
if res.object(forKey: "isToDo") != nil {
isTodo = res.object(forKey: "isToDo") as! Bool
}
if isTodo {
var str = res.object(forKey: "JobId") as! String
let index = str.index(str.startIndex, offsetBy: 1)
str = str.substring(from: index)
let prjId = Int(str)!
let project = app.dataManager.gProject.getProject(id: prjId)
let todoId = res.object(forKey: "TodoId") as! String
let todo = app.dataManager.gTodo.getTodo(id: Int(todoId)!)
self.project = project
self.todoItem = todo
app.dataManager.isCheckedin = true
self.des = res.object(forKey: "JobDescription") as? String
let startTime = res.object(forKey: "Dato2") as! String
DispatchQueue.main.async {
let ud = UserDefaults.standard
ud.set(true, forKey: "isCheckedIn")
ud.set( 1, forKey:"type")
ud.set( self.project.ID!, forKey: "projectId" )
ud.set( self.todoItem.ID! , forKey: "todoId" )
// print(" todo data is : \(self.todoItem.ID!)")
ud.set( self.des, forKey: "des")
ud.set( startTime,forKey: "startTime")
ud.set( startTime, forKey: "checkInTime" )
ud.synchronize()
self.hideHUD()
self.performSegue(withIdentifier: "goStartTodoFromSelect", sender: nil )
}
} else {
var jobId = res.object(forKey: "JobId") as! String
jobId = jobId.replacingOccurrences(of: "P", with: "")
self.des = res.object(forKey: "JobDescription") as? String
let jobCode = app.dataManager.gJobCode.getJobCode(id: Int(jobId)! )
self.jobCodeItem = jobCode
// let chekinTime = res.object(forKey: "Dato2") as! String
let startTime = "2019-05-15T19:45:00"
DispatchQueue.main.async {
app.dataManager.isCheckedin = true
let ud = UserDefaults.standard
ud.set(true, forKey: "isCheckedIn")
ud.set( 0, forKey:"type")
ud.set( jobId, forKey: "jobId" )
ud.set( startTime,forKey: "startTime")
ud.set( startTime, forKey: "checkInTime" )
if res.object(forKey: "JobDescription") != nil {
self.des = res.object(forKey: "JobDescription") as? String
ud.set( self.des, forKey: "des")
}
ud.synchronize()
DispatchQueue.main.async {
self.hideHUD()
self.performSegue(withIdentifier: "goStartJob", sender: nil )
}
}
}
} else {
DispatchQueue.main.async {
self.hideHUD()
// self.popToRoot()
for controller in self.navigationController!.viewControllers as Array {
if controller.isKind(of: SelectJobScreen.self) {
self.navigationController!.popToViewController(controller, animated: true)
break
}
}
}
}
}) { (error) in
DispatchQueue.main.async {
self.hideHUD()
// self.popToRoot()
for controller in self.navigationController!.viewControllers as Array {
if controller.isKind(of: SelectJobScreen.self) {
self.navigationController!.popToViewController(controller, animated: true)
break
}
}
}
}
} else {
print("Record Not Found")
}
}
Inside of that getPreviousStatus() functions getting null values , check it once using debugging
DispatchQueue.main.async {
# mainly in this thread getting error check it once
let ud = UserDefaults.standard
ud.set(true, forKey: "isCheckedIn")
ud.set( 1, forKey:"type")
ud.set( self.project.ID!, forKey: "projectId" )
ud.set( self.todoItem.ID! , forKey: "todoId" )
// print(" todo data is : \(self.todoItem.ID!)")
ud.set( self.des, forKey: "des")
ud.set( startTime,forKey: "startTime")
ud.set( startTime, forKey: "checkInTime" )
ud.synchronize()
self.hideHUD()
self.performSegue(withIdentifier: "goStartTodoFromSelect", sender: nil )
}

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.

Resources