I'm getting a random crash on my live app on Float to Int conversion line.
I can't figure out why it's crashing and can't reproduce it as it's random crash on live app. Any suggestion on how to fix crash?
Crash log
Crashed: com.apple.main-thread
0 MyApp 0x100703778 closure #1 in MyViewController.getBalance(isRefreshed:) + 797 (MyViewController.swift:797)
1 MyApp 0x1005c7670 closure #1 in closure #1 in fetchtBalance(completed:) + 185 (Utils.swift:185)
2 MyApp 0x10051ab10 thunk for #escaping #callee_guaranteed () -> () + 4335790864 (<compiler-generated>:4335790864)
3 libdispatch.dylib 0x1ae908b7c _dispatch_call_block_and_release + 32
4 libdispatch.dylib 0x1ae909fd8 _dispatch_client_callout + 20
5 libdispatch.dylib 0x1ae915cc8 _dispatch_main_queue_callback_4CF + 968
6 CoreFoundation 0x1aebdee0c __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
7 CoreFoundation 0x1aebd9b68 __CFRunLoopRun + 1980
8 CoreFoundation 0x1aebd9084 CFRunLoopRunSpecific + 480
9 GraphicsServices 0x1b8e27534 GSEventRunModal + 108
10 UIKitCore 0x1b2d49670 UIApplicationMain + 1940
11 MyApp 0x1004ec6b8 main + 20 (ClientMyProfileViewController.swift:20)
12 libdyld.dylib 0x1aea58e18 start + 4
Code
import UIKit
var balance: String!
var cost: String?
func getBalance () {
fetchBalance() { (result, error) in
guard let balanceFloatValue = Float(balance!) else {
print("Error")
return
}
guard let costFloat = Float(cost!) else {
print("Error")
return
}
let costPerSec = costFloat / 60
let talkTime = balanceFloatValue / costPerSec
let talkTimeInt = Int(talkTime) // Line No. 797 Crash here
// ....
}
}
The most likely cause for this error is the values themselves
let a:Float = 9999999999999999999999.9
let b = "0.000000000000000000001"
let c:Float = a/Float(b)!
let x = Int(c) // <- Crash here
0/0 will make you crash in: let c:Float = a/Float(b)! so thats not it, but anything else that can make talkTime outside of a Int will make you crash
This would also explain why you only encounter the error randomly since its only for values that make that division NaN or inf or something outside the int like bg2b said
I think you are force unwrapping the balance value. Try to unwrap the converted value like: „Float(balance)!“
Related
I am getting a crash reported in crashlytics about partial apply in closure. I have tried other answers that mainly focus on using [weak self] but that didn't help. However, i am not getting a crash on my device.
According to the report the crash is somewhere in the function where i show my dropDown here is the code
func showDropDown(_ names: [String], forResult result: SearchPatientResultResponnse) {
guard let vc = viewController
else { return }
self.searchedPatientNames = result.data?.patientSearchSuggestions
Helpers.showSearchDropdown(anchorView: vc.searchBar.searchTextField, dataSource: names, scrollToTop: true, completion: { [weak self] (i, item) in
guard let self = self else {
return
}
vc.searchBar.text = item
vc.dismissKeyboard()
self.selectedSearchPatient = self.searchedPatientNames?[i]
if let d = self.searchedPatientNames?[i].dob {
vc.dobTF.text = DateTimeFormatters.userUIDateFormatterInUTC.string(from: d)
}
self.search(self.selectedSearchFilter)
}, fetchPaginationData: { [weak self] in
guard let self = self, !self.isNameSearchLastPage, self.page != -1 else {
return
}
vc.searchBar.isLoadingWithoutSearchIcon = true
self.fetchPatientNameNextPage()
}, cancel: { [weak self] in
self?.resetPaginationParams()
})
}
This is the function from where i am calling this showDropDown function
func getQueryPatientResponse() {
guard let vc = viewController else {
return
}
SocketIOManager.shared.queryResponseForPatient = { [weak self] result in
var names: [String] = []
self?.isNameSearchLastPage = result.data?.isLastPage ?? true
self?.page = result.data?.pageNumber ?? -1
for data in result.data?.patientSearchSuggestions ?? [] {
var name = ""
if !data.middleName.isEmpty {
name = data.firstName + " " + data.middleName + " " + data.lastName
} else {
name = data.firstName + " " + (data.lastName)
}
names.append(name)
}
vc.searchBar.isLoadingWithoutSearchIcon = false
self?.page == 1 ? self?.showDropDown(names, forResult: result) : self?.updateDropDown(names, forResult: result)
}
}
This is the crash report from crashlytics:-
Crashed: com.apple.main-thread
0 Ovada CM - PT 0x639b0 closure #1 in VisitStatusViewModel.showDropDown(_:forResult:)
+ 4340890032 (<compiler-generated>:4340890032)
1 Ovada CM - PT 0x3f328 partial apply for closure #1 in static Helpers.showSearchDropdown(anchorView:dataSource:scrollToTop:completion:fetchPaginationData:cancel:)
+ 121 (Helpers.swift:121)
2 Ovada CM - PT 0x15604c DropDown.tableView(_:didSelectRowAt:)
+ 4341882956 (<compiler-generated>:4341882956)
3 Ovada CM - PT 0x156548 #objc DropDown.tableView(_:didSelectRowAt:)
+ 4341884232 (<compiler-generated>:4341884232)
4 UIKitCore 0xfe36d0 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:isCellMultiSelect:deselectPrevious:]
+ 1640
5 UIKitCore 0xfe3050 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:]
+ 112
6 UIKitCore 0xfe394c -[UITableView _userSelectRowAtPendingSelectionIndexPath:]
+ 316
7 UIKitCore 0x30c240 -[_UIAfterCACommitBlock run] + 64
8 UIKitCore 0x227770 -[_UIAfterCACommitQueue flush] + 200
9 UIKitCore 0x155eb0 _runAfterCACommitDeferredBlocks + 640
10 UIKitCore 0x15657c _cleanUpAfterCAFlushAndRunDeferredBlocks + 128
11 UIKitCore 0x156748 _afterCACommitHandler + 56
12 CoreFoundation 0x3e83c _CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION_ + 32
13 CoreFoundation 0xfa74 __CFRunLoopDoObservers + 616
14 CoreFoundation 0xaffc __CFRunLoopRun + 1012
15 CoreFoundation 0x1e250 CFRunLoopRunSpecific + 572
16 GraphicsServices 0x1988 GSEventRunModal + 160
17 UIKitCore 0x4e5a94 -[UIApplication _run] + 1080
18 UIKitCore 0x27efd4 UIApplicationMain + 336
19 Ovada CM - PT 0x6070 main + 14 (AppDelegate.swift:14)
20 ??? 0x1029dc4d0 (Missing)
Im dealing with this type of issue for the time and been stuck at this for weeks now. I already posted about finding location of error & tried to solve on my own after finding however I don't know what might be causing error here. Everything seems to be fine. Here's the error log file code:
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x000000018569e1a8
Exception Note: EXC_CORPSE_NOTIFY
Termination Reason: SIGNAL 5 Trace/BPT trap: 5
Terminating Process: exc handler [2868]
Triggered by Thread: 0
Kernel Triage:
VM - Compressor failed a blocking pager_get
VM - Compressor failed a blocking pager_get
VM - Compressor failed a blocking pager_get
VM - Compressor failed a blocking pager_get
VM - Compressor failed a blocking pager_get
Thread 0 name:
Thread 0 Crashed:
0 libswiftCore.dylib 0x000000018569e1a8 closure #1 in closure #1 in closure #1 in _assertionFailure(_:_:file:line:flags:) + 300 (AssertCommon.swift:96)
1 libswiftCore.dylib 0x000000018569df48 closure #1 in closure #1 in _assertionFailure(_:_:file:line:flags:) + 220 (AssertCommon.swift:89)
2 libswiftCore.dylib 0x000000018569d83c _assertionFailure(_:_:file:line:flags:) + 232 (AssertCommon.swift:85)
3 TestAlertApp 0x0000000102992da4 0x102834000 + 1437092
4 TestAlertApp 0x0000000102992320 0x102834000 + 1434400
5 TestAlertApp 0x000000010288c8a0 0x102834000 + 362656
6 AudioToolbox 0x000000018b839d1c AudioSessionRequestRecordPermission + 76 (AudioSession.cpp:0)
7 AudioSession 0x000000018a0640a8 softLink_AudioSessionRequestRecordPermission + 52 (SoftLinking_AudioToolbox_iOS.mm:48)
8 AudioSession 0x000000018a05af74 -[AVAudioSession requestRecordPermission:] + 116 (AVAudioSession_iOS.mm:1328)
9 TestAlertApp 0x0000000102991f50 0x102834000 + 1433424
10 TestAlertApp 0x000000010299187c 0x102834000 + 1431676
11 TestAlertApp 0x0000000102994f70 0x102834000 + 1445744
12 TestAlertApp 0x000000010288c37c 0x102834000 + 361340
13 TestAlertApp 0x0000000102b03b98 closure #1 in AlertMeViewController.initiateAlertMe(_:_:) + 1836 (AlertMeViewController.swift:311)
14 TestAlertApp 0x00000001029e724c 0x102834000 + 1782348
15 TestAlertApp 0x0000000102cfbb64 closure #1 in static SLWebRequest.post(url:params:headers:completionHandler:) + 640 (SLWebRequest.swift:55)
16 Alamofire 0x000000010352bcb0 partial apply for specialized closure #2 in closure #2 in closure #3 in closure #1 in DownloadRequest.response<A>(queue:responseSerializer:completionHandler:) + 48
17 Alamofire 0x00000001034c441c thunk for #escaping #callee_guaranteed () -> () + 20 (<compiler-generated>:0)
18 libdispatch.dylib 0x000000018091d924 _dispatch_call_block_and_release + 32 (init.c:1517)
19 libdispatch.dylib 0x000000018091f670 _dispatch_client_callout + 20 (object.m:560)
20 libdispatch.dylib 0x000000018092db70 _dispatch_main_queue_callback_4CF + 944 (inline_internal.h:2601)
21 CoreFoundation 0x0000000180c65d84 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CFRunLoop.c:1795)
22 CoreFoundation 0x0000000180c1ff5c __CFRunLoopRun + 2540 (CFRunLoop.c:3144)
23 CoreFoundation 0x0000000180c33468 CFRunLoopRunSpecific + 600 (CFRunLoop.c:3268)
24 GraphicsServices 0x000000019c7d738c GSEventRunModal + 164 (GSEvent.c:2200)
25 UIKitCore 0x00000001835d65d0 -[UIApplication _run] + 1100 (UIApplication.m:3493)
26 UIKitCore 0x0000000183354f74 UIApplicationMain + 364 (UIApplication.m:5047)
27 TestAlertApp 0x000000010289654c 0x102834000 + 402764
28 dyld 0x00000001032adaa4 start + 520 (dyldMain.cpp:879)
So based on this error, I found this code:
func initAudio(_ alertType: String) {
if self.checkPermission() == 0 {
if AVAudioSession.sharedInstance().outputVolume < 0.0625 {
let soundid = kSystemSoundID_Vibrate
AudioServicesPlaySystemSound(soundid)
self.deleteAllRecordings()
}else{
self.alerttype = alertType
self.deleteAllRecordings()
}
}else if self.checkPermission() == 1 {
gotoPermission(1)
}else{
gotoPermission(2)
}
}
Im totally lost here what might be wrong. Is it caused by AVAudioSession? or the two functions, self.deleteAllRecordings() or gotoPermission(1) or gotoPermission(2)?
Here's the code for deleteAllRecordings() just in case:
func deleteAllRecordings() {
print("\(#function)")
if self.recorder != nil {
self.recorder.stop()
}
let docsDir =
NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let fileManager = FileManager.default
do {
let files = try fileManager.contentsOfDirectory(atPath: docsDir)
let recordings = files.filter( { (name: String) -> Bool in
return name.hasSuffix("wav")
})
for i in 0 ..< recordings.count {
let path = docsDir + "/" + recordings[i]
print("removing \(path)")
do {
try fileManager.removeItem(atPath: path)
} catch {
NSLog("could not remove \(path)")
}
}
self.record()
} catch {
print("could not get contents of directory at \(docsDir)")
print(error.localizedDescription)
}
}
and code for gotoPermission():
func gotoPermission(_ grant: Int) {
if grant == 1 {
self.askForPermission()
} else {
if !self.initiatorStatus.InAlertMe && !self.initiatorStatus.InTimedAlert{
self.beepStartPlayer.play()
DispatchQueue.main.async {
Timer.scheduledTimer(withTimeInterval: Double(User().cUser.RecordSeconds), repeats: false, block: { _ in
if self.initiatorStatus.InAlert == true {
self.startBeep()
}
})
}
}
}
}
Is there something that might cause te crash in above code? According to log file, this is where the error occurs.
Out of 6 testers, one user experiences a crash on a line that only says
someDispatchQueue.sync { //Thread 0 crash
someDispatchQueue cannot be nil because it is being declared as
let someDispatchQueue = DispatchQueue(label: "SomeDispatchQueue") at the beginning of the class.
The only two reasons for a crash there that I could think of are
A) issues with how it's being called, namely like
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay) {
//a few functions in between
someDispatchQueue.sync {
Maybe you can't call a customQueue.sync{} within main.async{}? However, this tester is the only person to experience this crash whereas it's 99% certain that the other 5 testers run this function too - without any issues. It does run on my device without issues, too.
B) the indicated line of the log is off
Are Swift crash logs supposed to display the exact point of crashing? Or can it be a few lines off? The log says the following:
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x0000000100f2f95c
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [6599]
Triggered by Thread: 0
Thread 0 name:
Thread 0 Crashed:
0 AppName 0x0000000100f2f95c closure #1 in FileDB.prepareFile() + 508 (<compiler-generated>:0)
1 AppName 0x0000000100f39734 partial apply for thunk for #callee_guaranteed () -> () + 20 (<compiler-generated>:0)
2 AppName 0x0000000100f2ccf4 thunk for #escaping #callee_guaranteed () -> () + 20 (<compiler-generated>:0)
3 libdispatch.dylib 0x000000019770c33c _dispatch_client_callout + 20 (object.m:495)
4 libdispatch.dylib 0x00000001977191f4 _dispatch_lane_barrier_sync_invoke_and_complete + 60 (queue.c:996)
5 AppName 0x0000000100f2f6b4 FileDB.prepareFile() + 264 (FileDB.swift:138) //line 138 is the someDispatchQueue.sync {
6 AppName 0x0000000100f79844 ICEFrameworkHandler.initiateWrite() + 728 (ICEFrameworkHandler.swift:254)
7 AppName 0x0000000100f78e18 closure #1 in ICEFrameworkHandler.delayRun(delay:stamp:) + 140 (ICEFrameworkHandler.swift:164) //the function that calls the DispatchQueue.main.asyncAfter
8 AppName 0x0000000100f7e508 thunk for #escaping #callee_guaranteed () -> () + 28 (<compiler-generated>:0)
9 libdispatch.dylib 0x000000019770c33c _dispatch_client_callout + 20 (object.m:495)
10 libdispatch.dylib 0x000000019770eaf8 _dispatch_continuation_pop + 408 (inline_internal.h:2484)
11 libdispatch.dylib 0x000000019771f624 _dispatch_source_invoke + 1224 (source.c:568)
12 libdispatch.dylib 0x00000001977184f0 _dispatch_main_queue_callback_4CF + 560 (inline_internal.h:2525)
13 CoreFoundation 0x00000001979e76b0 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CFRunLoop.c:1749)
14 CoreFoundation 0x00000001979e22c8 __CFRunLoopRun + 1708 (CFRunLoop.c:3069)
15 CoreFoundation 0x00000001979e18f4 CFRunLoopRunSpecific + 480 (CFRunLoop.c:3192)
16 GraphicsServices 0x00000001a1df8604 GSEventRunModal + 164 (GSEvent.c:2246)
17 UIKitCore 0x000000019bbb5358 UIApplicationMain + 1944 (UIApplication.m:4823)
18 AppName 0x0000000100f150b4 main + 68 (AppDelegate.swift:19)
19 libdyld.dylib 0x000000019785d2dc start + 4
#matt
let someDispatchQueue = DispatchQueue(label: "SomeDispatchQueue")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
someDispatchQueue.sync {
print("someDispatchQueue.sync") //prints first, no exception
}
print("end of asyncAfter()") //prints second, reaches statement without exception
}
This line:
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay) {
...proves that when we get here, we are on the main queue. Okay, now:
someDispatchQueue.sync {
Whoa! You must never say sync when you are on the main queue. That's because sync means “Block me; I want to stop and wait for this other queue to finish this next task.” But “me” is the main queue; you must never block the main queue.
I've a random crash in live app. It crashes on guard statement. Following is the code snippet. I'm not able to understand why it crashes on guard which was suppose to guard against crashes like this?
How to fix this issue or how do I go about investigating it?
Crashlytics log
Crashed: com.apple.main-thread
EXC_BREAKPOINT 0x0000000102419850
0 myApp 0x102426f50 MessageVC.validate() + 101 (MessageVC.swift:101)
1 myApp 0x1024272d8 #objc MessageVC.buttonTapped(_:) + 239 (MessageVC.swift:239)
2 UIKitCore 0x1a6a8d9ac <redacted> + 96
3 UIKitCore 0x1a64c3fbc <redacted> + 240
4 UIKitCore 0x1a64c4320 <redacted> + 408
5 UIKitCore 0x1a64c333c <redacted> + 520
6 UIKitCore 0x1a6674a58 <redacted> + 7636
7 CoreFoundation 0x1a2983e68 <redacted> + 32
8 CoreFoundation 0x1a297ed54 <redacted> + 416
9 CoreFoundation 0x1a297f320 <redacted> + 1308
10 CoreFoundation 0x1a297eadc CFRunLoopRunSpecific + 464
11 GraphicsServices 0x1ac91f328 GSEventRunModal + 104
12 UIKitCore 0x1a6a8c63c UIApplicationMain + 1936
13 myApp 0x1023eb850 main + 21 (ProfileVC.swift:11)
14 libdyld.dylib 0x1a2808360 <redacted> + 4
Model.swift
struct ProfileStatus: Decodable {
var status: Bool?
var error: String?
}
MessageVC.swift
var profileStatus: ProfileStatus!
func validate() -> Bool {
guard let status = profileStatus.status else { // Line no. 101, Crash here
return true
}
// Do something...
}
#IBAction func buttonTapped(_ sender: UIButton) {
if validate() { // Line no. 239
// Do something..
}
}
ProfileVC.swift
class ProfileVC: UIViewController {
#IBOutlet weak var textField: MyTextField! // Line no. 11
// ....
}
The reason of crash in force unwrap
var profileStatus: ProfileStatus! // << here is the reason
so you need to find in other code where ownership is lost, and, which is anyway good practice
var profileStatus: ProfileStatus? // use optional and unwrap where needed conditonally
func validate() -> Bool {
guard let status = profileStatus?.status else {
I have a simple class func for adding SKEmitterNode on many different occasions.
I cannot reproduce steps when the exception occurs. It happens rarely and quite randomly. I can call this method 500 times without an error or in some cases error can happen after 1 or 2 call, etc.
The problem/exception line is:
root?.addChild(sparks)
Below is the method and stack trace. I have no idea how to debug this. I've tried many different things but without success.
Any ideas ?
class func setSimpleSparksEffect(root:SKNode?, color:UIColor, position:CGPoint)
{
if CGPointEqualToPoint(position, CGPointZero)
{
return
}
let sparks = SKEmitterNode(fileNamed: "SimpleSparks")
sparks.alpha = GameObjectsDefaultAlpha
sparks.particleColorSequence = nil
sparks.particleColorBlendFactor = 1.0
sparks.particleColor = color
sparks.position = position
sparks.zPosition = SparksElementsZPosition
root?.addChild(sparks)
sparks.runAction(SKAction.waitForDuration(NSTimeInterval(EmmiterSimpleShortDuration)), completion: { () -> Void in
sparks.runAction(SKAction.fadeOutWithDuration(NSTimeInterval(FactorSparksFadeOutDuration)), completion: { () -> Void in
sparks.removeAllActions()
sparks.removeAllChildren()
sparks.removeFromParent()
})
})
}
And stack trace:
Thread : Crashed: com.apple.main-thread
0 libc++abi.dylib 0x0000000199944ce4 __dynamic_cast + 52
1 SpriteKit 0x000000018ab63f58 __15-[SKNode scene]_block_invoke + 60
2 SpriteKit 0x000000018ab63f58 __15-[SKNode scene]_block_invoke + 60
3 SpriteKit 0x000000018ab28038 SKCNode::walkUp(void (SKCNode*, bool*) block_pointer, bool) + 76
4 SpriteKit 0x000000018ab63eac -[SKNode scene] + 132
5 SpriteKit 0x000000018ab643ac -[SKNode insertChild:atIndex:] + 356
6 SpriteKit 0x000000018ab64224 -[SKNode addChild:] + 76
7 DodgeMaster 0x00000001000f1d80 static DodgieCommon.setSimpleSparksEffect(SKNode?, color : UIColor, position : CGPoint) -> () (DodgieCommon.swift:275)
8 DodgeMaster 0x00000001000d2bc4 GameLevel.(gameLogicGoalerHitmeContact(GameLevel) -> (NSNotification) -> ()).(closure #1) (GameLevel.swift:502)
9 DodgeMaster 0x0000000100125018 static Helper.(runAsyncOnMain(Helper.Type) -> (() -> ()) -> ()).(closure #1) (Helper.swift:270)
10 DodgeMaster 0x00000001000b41c4 thunk (Pointoser.swift)
11 libdispatch.dylib 0x000000019aa917b0 _dispatch_call_block_and_release + 24
12 libdispatch.dylib 0x000000019aa91770 _dispatch_client_callout + 16
13 libdispatch.dylib 0x000000019aa96e20 _dispatch_main_queue_callback_4CF + 1844
14 CoreFoundation 0x000000018574c258 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
15 CoreFoundation 0x000000018574a0c0 __CFRunLoopRun + 1628
16 CoreFoundation 0x0000000185678dc0 CFRunLoopRunSpecific + 384
17 GraphicsServices 0x00000001907cc088 GSEventRunModal + 180
18 UIKit 0x000000018ad52f60 UIApplicationMain + 204
19 DodgeMaster 0x000000010011de24 main (AppDelegate.swift:22)
20 libdyld.dylib 0x000000019aac28b8 start + 4
Another person on here had a similar problem which I think you may encountering too... I've tailored my response on that post for yours.
let sparksFile: String = NSBundle.mainBundle().pathForResource("SimpleSparks", ofType: "sks")!
let sparks = NSKeyedUnarchiver.unarchiveObjectWithFile(explosionFile) as! SKEmitterNode
sparks.alpha = GameObjectsDefaultAlpha
sparks.particleColorSequence = nil
sparks.particleColorBlendFactor = 1.0
sparks.particleColor = color
sparks.position = position
sparks.zPosition = SparksElementsZPosition
self.root?.addChild(sparks)