Crashed: com.apple.main-thread - App crashes randomly on guard statement - ios

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 {

Related

EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000***

During few days I am seeing a firebase crash analytic issue (given below) in my console. I am surfing a log but didn't get any solution. I am not sure the crush Mocking line-1 and line-2 (inside the self.addTransferOperation() function). If it is 'addOperation' related issue (line-2), what will its solution then. How it is possible to become the operation (transferOperation) nil. Advance thanks for your help.
line-1:
_ = self.addTransferOperation(device: device, deviceIndex:index, dataTransferCategory:OMVitalDataTransferCategory.bloodPressure)
Line-2:
func addTransferOperation(device: ConnectedDevice, deviceIndex:Int, dataTransferCategory:OMVitalDataTransferCategory = OMVitalDataTransferCategory.all) -> ConnectivityTransferOperation {
let transferOperation = ConnectivityTransferOperation()
// transferOperation.isUserNotify = device == sortedDeviceList.last ? notifyUser : false
let connectedDevice = ConnectedDevice(value : device)
transferOperation.device = ConnectedDevice(value : device)
transferOperation.transferDataType = dataTransferCategory
transferOperation.completionBlock = {
LogManager.shared.addLog(logString: "completion of transfer operation",localName: connectedDevice.deviceLocalName, uuid: connectedDevice.uuid)
// Remove first item
if !self.pendingOperations.syncInProgress.isEmpty {
self.pendingOperations.syncInProgress.removeAll(where: {$0 == transferOperation})
}
// Empty queue
if self.pendingOperations.syncInProgress.isEmpty {
// update autosync timer if Manual sync
if (self.isManualSync) {
self.updateSyncTimer()
}
}
// Reset bluetooth state
self.resetBluetoothState()
DispatchQueue.main.async {
// Set error from transfer operation and set flag to check if it happened in transfer operation
let transferOperationDetails: [String : Any] = [ConnectivityConfiguration.error: transferOperation.error,
ConnectivityConfiguration.isTransferOperation:true]
// post notification for stop data transfer with transfer error operation object
NotificationCenter.default.post(name: .dataTransferStop,
object: transferOperationDetails)
}
}
LogManager.shared.addLog(logString: "Add transfer operation for device \(device.displayName)",localName: connectedDevice.deviceLocalName, uuid: connectedDevice.uuid)
// Add operation and start
self.pendingOperations.syncInProgress.append(transferOperation)
if deviceIndex > 0 {
// add dependency
transferOperation.addDependency(self.pendingOperations.syncInProgress[deviceIndex-1])
}
self.pendingOperations.syncQueue.addOperation(transferOperation)
return transferOperation
}
Crash:
Crashed: com.apple.main-thread
0 Foundation 0x114ea8 ____addOperations_block_invoke.567 + 680
1 Foundation 0x113858 __addOperations + 1288
2 GrandApp 0x7bd3d8 ConnectivityManager.addTransferOperation(device:deviceIndex:dataTransferCategory:) + 2411 (ConnectivityManager.swift:2411)
3 GrandApp 0x7bc3f0 ConnectivityManager.transferOperation(withDevices:notifyUser:isManualSync:) + 4313269232 (<compiler-generated>:4313269232)
4 GrandApp 0x7a6770 ConnectivityManager.startTransferOperation(notifyUser:device:syncAllData:isBeaconFlow:) + 4313180016 (<compiler-generated>:4313180016)
5 GrandApp 0x6c4aa4 closure #1 in DashboardViewController.refreshAction() + 1096 (DashboardViewController.swift:1096)
6 GrandApp 0x7cc37c specialized ConnectivityManager.isSyncing(withStop:completion:) + 4313334652 (<compiler-generated>:4313334652)
7 GrandApp 0x6c4218 DashboardViewController.refreshAction() + 4312252952 (<compiler-generated>:4312252952)
8 GrandApp 0x6c4aec #objc DashboardViewController.refreshAction() + 4312255212 (<compiler-generated>:4312255212)
9 UIKitCore 0x8be300 -[UIApplication sendAction:to:from:forEvent:] + 96
10 UIKitCore 0x367424 -[UIControl sendAction:to:forEvent:] + 80
11 UIKitCore 0x367744 -[UIControl _sendActionsForEvents:withEvent:] + 440
12 UIKitCore 0x3667b0 -[UIControl touchesEnded:withEvent:] + 568
13 UIKitCore 0x8f55c4 -[UIWindow _sendTouchesForEvent:] + 2108
14 UIKitCore 0x8f67ec -[UIWindow sendEvent:] + 3140
15 UIKitCore 0x8d685c -[UIApplication sendEvent:] + 340
16 UIKitCore 0x99c9d4 __dispatchPreprocessedEventFromEventQueue + 1768
17 UIKitCore 0x99f100 __handleEventQueueInternal + 4828
18 UIKitCore 0x998330 __handleHIDEventFetcherDrain + 15
19 CoreFoundation 0xaaf1c CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 24
20 CoreFoundation 0xaae9c __CFRunLoopDoSource0 + 88
21 CoreFoundation 0xaa784 __CFRunLoopDoSources0 + 176
22 CoreFoundation 0xa56c0 __CFRunLoopRun + 1004
23 CoreFoundation 0xa4fb4 CFRunLoopRunSpecific + 436
24 GraphicsServices 0xa79c GSEventRunModal + 104
25 UIKitCore 0x8bcc38 UIApplicationMain + 212
26 GrandApp 0x1db0c main + 19 (AppDelegate.swift:19)
27 libdyld.dylib 0x18e0 start + 4
ConnectivityTransferOperation.swift
import UIKit
import OMConnectivityLibrary
/// Transfer operation for connectivity
class ConnectivityTransferOperation : ConnectivityOperation {
override func main() {
guard isCancelled == false else {
finish(true)
return
}
self.executing(true)
}
override func end() {
// Super call
super.end()
}
}
ConnectivityOperation.swift
import UIKit
import OMConnectivityLibrary
class ConnectivityOperation: Operation {
/// Making operation queue async
override var isAsynchronous: Bool {
get {
return true
}
}
private var _executing = false {
willSet {
willChangeValue(forKey: "isExecuting")
}
didSet {
didChangeValue(forKey: "isExecuting")
}
}
private var _finished = false {
willSet {
willChangeValue(forKey: "isFinished")
}
didSet {
didChangeValue(forKey: "isFinished")
}
}
override var isExecuting: Bool {
return _executing
}
override var isFinished: Bool {
return _finished
}
func executing(_ executing: Bool) {
_executing = executing
}
func finish(_ finished: Bool) {
_finished = finished
}
func end() {
self.finish(true)
self.executing(false)
}
}

IGListKit - Crash on Load More, after network call, updating existing array

General information
IGListKit version: 3.4.0
iOS version(s): 12
CocoaPods/Carthage version: 1.5.3
Xcode version: 10.1
Devices/Simulators affected: All
Reproducible in the demo project? (Yes/No): No demo project
Hello.
I have this issue with IGList kit.
So in my project i have a "Loading more" functionality about images downloaded from my API, paginated.
So there is a class which holds the images
class ProfileImages: ListDiffable {
var nextMaxID: String?
var images: [Images]?
init(nextMaxID: String? = nil, images: [Images]? = []) {
self.images = images
self.nextMaxID = nextMaxID
}
func diffIdentifier() -> NSObjectProtocol {
return (nextMaxID ?? "ProfileImages") as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
guard self !== object else { return true }
guard let object = object as? ProfileImages else { return false }
return nextMaxID == object.nextMaxID
}
}
In my viewModel i have this function which gives me the above class but with the newest images array without the previous ones, since its paginated.
func updateUserImages(with userID: Int?, and nextMaxID: String, onSuccess: #escaping (ProfileImages) -> Void) {
userService.getUserImages(with: userID, nextMaxId: nextMaxID) { (feedResponse) in
let newProfileImages = ProfileImages(nextMaxID: feedResponse.nextMaxId, images: feedResponse.items)
onSuccess(newProfileImages)
}
}
And in my View Controller, in the scroll delegate of adapter, I have your paradigm from LoadMoreSectionController
extension ProfileViewController: UIScrollViewDelegate {
func scrollViewWillEndDragging(_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
guard let object = self.profileViewModel.viewData.value[1] as? ProfileImages,
let nextMaxID = object.nextMaxID,
var oldImages = object.images else { return }
let distance = scrollView.contentSize.height - (targetContentOffset.pointee.y + scrollView.bounds.height)
if !loading && distance < 200 {
loading = true
adapter.performUpdates(animated: true, completion: nil)
DispatchQueue.global(qos: .default).async {
DispatchQueue.main.async {
self.profileViewModel.updateUserImages(with: self.userService.user.pk, and: nextMaxID, onSuccess: { profileImages in
self.loading = false
oldImages.append(contentsOf: profileImages.images ?? []) // here i update the previews array by appending the new arrays
object.images = oldImages // and here i replace the previews array with the new one which has all the images.
object.nextMaxID = profileImages.nextMaxID
self.adapter.performUpdates(animated: true, completion: nil) // Although if i use `self.adapter.reloadData()` its not crashing although i read on the docs that it's not a proper way to reload stuff.
})
}
}
}
}
}
And when i scroll down it crashes.
2019-02-03 15:31:00.520794+0200 ProjectName [20694:7628667] *** Assertion failure in -[IGListAdapter _visibleSectionControllersFromLayoutAttributes](), /Users/trypow-mac/Desktop/ProjectName/Pods/IGListKit/Source/IGListAdapter.m:515
2019-02-03 15:31:00.527576+0200 ProjectName[20694:7628667] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Section controller nil for cell in section 1'
*** First throw call stack:
(
0 CoreFoundation 0x000000010a3161bb __exceptionPreprocess + 331
1 libobjc.A.dylib 0x00000001098b4735 objc_exception_throw + 48
2 CoreFoundation 0x000000010a315f42 +[NSException raise:format:arguments:] + 98
3 Foundation 0x0000000104fdf940 -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 166
4 IGListKit 0x000000010568eb99 -[IGListAdapter _visibleSectionControllersFromLayoutAttributes] + 1273
5 IGListKit 0x000000010568e67c -[IGListAdapter visibleSectionControllers] + 540
6 IGListKit 0x00000001056935a4 -[IGListAdapter scrollViewDidScroll:] + 196
7 UIKitCore 0x000000011333ba5b -[UIScrollView(UIScrollViewInternal) _notifyDidScroll] + 66
8 UIKitCore 0x00000001133220ef -[UIScrollView setContentOffset:] + 1007
9 UIKitCore 0x00000001133337e5 -[UIScrollView _smoothScrollWithUpdateTime:] + 2967
10 UIKitCore 0x0000000113333bb6 -[UIScrollView _smoothScrollDisplayLink:] + 379
11 QuartzCore 0x00000001063300a2 _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy + 818
12 QuartzCore 0x00000001063fcbb9 _ZL22display_timer_callbackP12__CFMachPortPvlS1_ + 297
13 CoreFoundation 0x000000010a24f5a6 __CFMachPortPerform + 150
14 CoreFoundation 0x000000010a27bf69 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
15 CoreFoundation 0x000000010a27b5bb __CFRunLoopDoSource1 + 459
16 CoreFoundation 0x000000010a275b2e __CFRunLoopRun + 2526
17 CoreFoundation 0x000000010a274e11 CFRunLoopRunSpecific + 625
18 GraphicsServices 0x000000010cef51dd GSEventRunModal + 62
19 UIKitCore 0x0000000112ec181d UIApplicationMain + 140
20 ProjectName 0x0000000102022424 main + 68
21 libdyld.dylib 0x000000010b3ee575 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Am I missing something ?

app crash when using multiple inout param in function

My application crash when i use below code.
var char : Character = "1"
var char2 : Character = "1"
func changeChar( char1: inout Character,char2: inout Character) {
char = "b"
char2 = "b"
}
override func viewDidAppear(_ animated: Bool) {
print(char,char2)
changeChar(char1: &char, char2: &char2)
print(char,char2)
}
Error:
Simultaneous accesses to 0x100e0ec50, but modification requires exclusive access.
Previous access (a modification) started at PPlayerNew`ViewController.viewDidAppear(_:) + 340 (0x1000eeda8).
Current access (a modification) started at:
0 libswiftCore.dylib 0x00000001004b9a38 swift_beginAccess + 468
1 PPlayerNew 0x00000001000ee960 ViewController.char.setter + 92
2 PPlayerNew 0x00000001000eebbc ViewController.changeChar(char1:char2:) + 96
3 PPlayerNew 0x00000001000eec54 ViewController.viewDidAppear(_:) + 436
4 PPlayerNew 0x00000001000eef98 #objc ViewController.viewDidAppear(_:) + 64
5 UIKit 0x000000018b3cc5c0 <redacted> + 856
6 UIKit 0x000000018b439630 <redacted> + 44
7 UIKit 0x000000018b43959c <redacted> + 92
8 UIKit 0x000000018b641470 <redacted> + 556
9 UIKit 0x000000018b633420 <redacted> + 528
10 UIKit 0x000000018b64c7b4 <redacted> + 152
11 CoreFoundation 0x00000001852312f8 <redacted> + 20
12 CoreFoundation 0x0000000185230a08 <redacted> + 288
13 CoreFoundation 0x000000018522e6c0 <redacted> + 728
14 CoreFoundation 0x000000018515ebfc CFRunLoopRunSpecific + 424
15 GraphicsServices 0x0000000186bc9010 GSEventRunModal + 100
16 UIKit 0x000000018b419bcc UIApplicationMain + 208
17 PPlayerNew 0x00000001000f0570 main + 76
18 libdyld.dylib 0x000000018416d598 <redacted> + 4
But when i use single param function, like below. code is working
func changeChar( char1: inout Character) {
char = "b"
}
So my main goal is to use inout function with multiple parameters.How can i do this or what's wrong with my code?
Thank You.
You’re changing the property char in your func instead of the parameter char1.

Initializing realm globally causing a crash

I have a swift app with realm integrated to it. I am declaring the realm globally in the AppDelegate.swift as shown below in the code. When I execute this application, My app runs fine on the devices and even in the test mode.
Issue:
After my app submission, the Apple review board rejected app and the symbolicated crash logs pointed the initialisation of the realm.
Below is the code, what am I possibly doing wrong?
import UIKit
import CoreData
import Firebase
import UserNotifications
import Fabric
import RealmSwift
var uiRealm = try! Realm()
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
var tokenExists = false
let imageDb = DigitalFingerprint()
var uid: String!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
#if DEVELOPMENT
print("Development Mode Started")
let filePath = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist")
guard let fileopts = FirebaseOptions.init(contentsOfFile: filePath!)
else {
fatalError("Couldn't load config file")
}
FirebaseApp.configure(options: fileopts)
#else
print("Production Mode Started")
FirebaseApp.configure()
#endif
Auth.auth().addStateDidChangeListener { (auth, user) in
if (user != nil) {
print("User is there")
self.uid = KeychainWrapper.standard.string(forKey: KEY_UID)
} else {
print("user signed out")
DB_URL.removeAllObservers()
DispatchQueue.main.async {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "starts") as? BootVC
var topRootViewController: UIViewController = (UIApplication.shared.keyWindow?.rootViewController)!
while((topRootViewController.presentedViewController) != nil){
topRootViewController = topRootViewController.presentedViewController!
}
topRootViewController.present(vc!, animated: true, completion: nil)
}
}
}
if uid != nil {
checkforAccess()
}
return true
}
Following is the Real object, DigitalFingerprint.swift
import Foundation
import RealmSwift
import UIKit
class DigitalFingerprint: Object {
#objc dynamic var imageData: Data? = nil
#objc dynamic var fid : String? = nil
#objc dynamic var uid : String? = nil
override static func primaryKey() -> String {
return "uid"
}
}
extension DigitalFingerprint {
func writeToRealm(){
try! uiRealm.write {
uiRealm.add(self, update: true)
}
}
func DeleteFromRealm(object: Results<DigitalFingerprint>){
try! uiRealm.write {
uiRealm.delete(object)
}
}
}
crash Logs received by apple review board. :
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Triggered by Thread: 0
Application Specific Information:
abort() called
Filtered syslog:
None found
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x00000001830142e8 __pthread_kill + 8
1 libsystem_pthread.dylib 0x00000001831292f8 pthread_kill$VARIANT$mp + 396
2 libsystem_c.dylib 0x0000000182f83060 __abort + 152
3 libsystem_c.dylib 0x0000000182f82fc8 __abort + 0
4 libc++abi.dylib 0x000000018271f068 __cxa_bad_cast + 0
5 libc++abi.dylib 0x000000018271f1f8 default_terminate_handler+ 8696 () + 280
6 libobjc.A.dylib 0x0000000182748820 _objc_terminate+ 34848 () + 140
7 SpotMi 0x0000000100dc7d78 CLSTerminateHandler() + 1260920 (CLSException.mm:314)
8 libc++abi.dylib 0x000000018273754c std::__terminate(void (*)+ 107852 ()) + 16
9 libc++abi.dylib 0x00000001827375b8 std::terminate+ 107960 () + 60
10 Realm 0x0000000101f94a00 realm::Realm::open_with_config(realm::Realm::Config const&, std::__1::unique_ptr<realm::Replication, std::__1::default_delete<realm::Replication> >&, std::__1::unique_ptr<realm::SharedGroup, std::__1::default_delete<realm::SharedGroup> >&, std::__1::unique_ptr<realm::Group, std::__1::default_delete<realm::Group> >&, realm::Realm*) + 985600 (memory:3006)
11 Realm 0x0000000101f944e0 realm::Realm::Realm(realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator>) + 984288 (shared_realm.cpp:55)
12 Realm 0x0000000101ed9658 realm::Realm::make_shared_realm(realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator>)::make_shared_enabler::make_shared_enabler(realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator>) + 218712 (shared_realm.hpp:304)
13 Realm 0x0000000101ed94cc std::__1::shared_ptr<realm::Realm::make_shared_realm(realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator>)::make_shared_enabler> std::__1::shared_ptr<realm::Realm::make_shared_realm(realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator>)::make_shared_enabler>::make_shared<realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator> >(realm::Realm::Config&&, std::__1::shared_ptr<realm::_impl::RealmCoordinator>&&) + 218316 (memory:2172)
14 Realm 0x0000000101ed56a4 realm::_impl::RealmCoordinator::get_realm(realm::Realm::Config) + 202404 (realm_coordinator.cpp:229)
15 Realm 0x0000000101f965f0 realm::Realm::get_shared_realm(realm::Realm::Config) + 992752 (shared_realm.cpp:250)
16 Realm 0x0000000101f7016c +[RLMRealm realmWithConfiguration:error:] + 835948 (RLMRealm.mm:400)
17 RealmSwift 0x00000001023911e4 Realm.init() + 152036 (Realm.swift:0)
18 RealmSwift 0x0000000102391178 Realm.__allocating_init() + 151928 (Realm.swift:0)
19 SpotMi 0x0000000100c9be14 globalinit_33_E3853139275E4567E078AE3BFE0165A3_func0 + 32276 (AppDelegate.swift:23)
20 libdispatch.dylib 0x0000000182e7ea14 _dispatch_client_callout + 16
21 libdispatch.dylib 0x0000000182e82240 dispatch_once_f$VARIANT$mp + 60
22 SpotMi 0x0000000100cc2254 FeedVC.viewDidLoad() + 189012 (FeedVC.swift:84)
23 SpotMi 0x0000000100cc2650 #objc FeedVC.viewDidLoad() + 190032 (FeedVC.swift:0)
24 UIKit 0x000000018c9e3ae8 -[UIViewController loadViewIfRequired] + 1040
25 UIKit 0x000000018c9e36c0 -[UIViewController view] + 28
26 UIKit 0x000000018c9ea28c -[UIWindow addRootViewControllerViewIfPossible] + 136
27 UIKit 0x000000018c9e74ec -[UIWindow _setHidden:forced:] + 272
28 UIKit 0x000000018ca563a0 -[UIWindow makeKeyAndVisible] + 48
29 UIKit 0x000000018cc43d10 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3620
30 UIKit 0x000000018cc48aa8 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1712
31 UIKit 0x000000018cee42d4 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 800
32 UIKit 0x000000018d1bc12c +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 160
33 UIKit 0x000000018cee3f38 -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 252
34 UIKit 0x000000018cee4798 -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 732
35 UIKit 0x000000018d6697d0 __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 260
36 UIKit 0x000000018d669674 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 448
37 UIKit 0x000000018d3d72dc __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 220
38 UIKit 0x000000018d5703dc _performActionsWithDelayForTransitionContext + 112
39 UIKit 0x000000018d3d718c -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 252
40 UIKit 0x000000018d1bb78c -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 364
41 UIKit 0x000000018cc471ec -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 540
42 UIKit 0x000000018d05cde8 -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 364
43 FrontBoardServices 0x0000000185bc61f0 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 364
44 FrontBoardServices 0x0000000185bceaf8 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 224
45 libdispatch.dylib 0x0000000182e7ea14 _dispatch_client_callout + 16
46 libdispatch.dylib 0x0000000182e86200 _dispatch_block_invoke_direct$VARIANT$mp + 288
47 FrontBoardServices 0x0000000185bfa7f8 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 36
48 FrontBoardServices 0x0000000185bfa49c -[FBSSerialQueue _performNext] + 404
49 FrontBoardServices 0x0000000185bfaa38 -[FBSSerialQueue _performNextFromRunLoopSource] + 56
50 CoreFoundation 0x00000001834aa97c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
51 CoreFoundation 0x00000001834aa8fc __CFRunLoopDoSource0 + 88
52 CoreFoundation 0x00000001834aa184 __CFRunLoopDoSources0 + 204
53 CoreFoundation 0x00000001834a7d5c __CFRunLoopRun + 1048
54 CoreFoundation 0x00000001833c7e58 CFRunLoopRunSpecific + 436
55 GraphicsServices 0x0000000185274f84 GSEventRunModal + 100
56 UIKit 0x000000018ca4767c UIApplicationMain + 236
57 SpotMi 0x0000000100c99b4c main + 23372 (SurpriseCell.swift:26)
58 libdyld.dylib 0x0000000182ee456c start + 4
And I am calling this function also in my initialviewcontroller(Feedvc), in the viewDidAppear()
The flow of my program is
1.load feedvc
if the user is nil
Go to the bootVc(thats called from app delegate)
Again what exactly am i doing wrong?
Also, will just declaring a variable of type realm globally and then initialzing the variable in didFinishLaunching() be a better option?
Thanks!
Well, it is not a good idea to create variables outside the class. Try to create
var uiRealm = try! Realm()
inside the AppDelegate class. And use (UIApplication.shared.delegate as! AppDelegate).uiRealm in other classes.

'NSInvalidArgumentException', reason: '-[BanGuayaPrototype.ViewController getTextId:]: unrecognized selector sent to instance 0x7fe5f69027d0'

I am a bit new in the development of native apps for iOS. I am working on Swift 4 and when trying to move to another screen from my login, I am generating the following error:
BanGuayaPrototype[11289:1143773] -[BanGuayaPrototype.ViewController getTextId:]: unrecognized selector sent to instance 0x7fe5f69027d0 2018-01-10 14:40:06.213350-0500
BanGuayaPrototype[11289:1143773] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[BanGuayaPrototype.ViewController getTextId:]: unrecognized selector sent to instance 0x7fe5f69027d0'
* First throw call stack: (
0 CoreFoundation 0x000000010d42512b exceptionPreprocess + 171
1 libobjc.A.dylib 0x0000000108ce3f41 objc_exception_throw + 48
2 CoreFoundation 0x000000010d4a6024 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 UIKit 0x0000000109a52f51 -[UIResponder doesNotRecognizeSelector:] + 295
4 CoreFoundation 0x000000010d3a7f78 ___forwarding_ + 1432
5 CoreFoundation 0x000000010d3a7958 _CF_forwarding_prep_0 + 120
6 UIKit 0x0000000109820972 -[UIApplication sendAction:to:from:forEvent:] + 83
7 UIKit 0x000000010999fc3c -[UIControl sendAction:to:forEvent:] + 67
8 UIKit 0x000000010999ff59 -[UIControl _sendActionsForEvents:withEvent:] + 450
9 UIKit 0x000000010a548407 -[UITextField _resignFirstResponder] + 155
10 UIKit 0x0000000109a52939 -[UIResponder _finishResignFirstResponder] + 286
11 UIKit 0x000000010a548026 -[UITextField _finishResignFirstResponder] + 48
12 UIKit 0x0000000109a529e8 -[UIResponder resignFirstResponder] + 140
13 UIKit 0x000000010a547ef6 -[UITextField resignFirstResponder] + 135
14 UIKit 0x00000001098d6463 -[UIView(Hierarchy) _removeFirstResponderFromSubtree] + 167
15 UIKit 0x00000001098d6a73 UIViewWillBeRemovedFromSuperview + 72
16 UIKit 0x00000001098d685d -[UIView(Hierarchy) removeFromSuperview] + 95
17 UIKit 0x000000010999b591 __71-[UIPresentationController _initViewHierarchyForPresentationSuperview:]_block_invoke.674 + 858
18 UIKit 0x0000000109994b5b -[UIPresentationController transitionDidFinish:] + 111
19 UIKit 0x0000000109c1cc1e -[_UICurrentContextPresentationController transitionDidFinish:] + 44
20 UIKit 0x0000000109998f4f __56-[UIPresentationController runTransitionForCurrentState]_block_invoke_2 + 183
21 UIKit 0x000000010a58d088 -[_UIViewControllerTransitionContext completeTransition:] + 102
22 UIKit 0x0000000109991dba -[UITransitionView notifyDidCompleteTransition:] + 251
23 UIKit 0x0000000109991a31 -[UITransitionView _didCompleteTransition:] + 1397
24 UIKit 0x00000001099940c8 -[UITransitionView _transitionDidStop:finished:] + 104
25 UIKit 0x00000001098b56c4 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 343
26 UIKit 0x00000001098b5d23 -[UIViewAnimationState animationDidStop:finished:] + 293
27 UIKit 0x00000001098b5dd7 -[UIViewAnimationState animationDidStop:finished:] + 473
28 QuartzCore 0x00000001096696bd _ZN2CA5Layer23run_animation_callbacksEPv + 323
29 libdispatch.dylib 0x000000010e54733d _dispatch_client_callout + 8
30 libdispatch.dylib 0x000000010e5525f9 _dispatch_main_queue_callback_4CF + 628
31 CoreFoundation 0x000000010d3e7e39 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 9
32 CoreFoundation 0x000000010d3ac462 __CFRunLoopRun + 2402
33 CoreFoundation 0x000000010d3ab889 CFRunLoopRunSpecific + 409
34 GraphicsServices 0x0000000110ff39c6 GSEventRunModal + 62
35 UIKit 0x000000010981f5d6 UIApplicationMain + 159
36 BanGuayaPrototype 0x00000001083a31d7 main + 55
37 libdyld.dylib 0x000000010e5c3d81 start + 1
38 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)
Below are the classes involved:
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var getText: UITextField!
var cliente = Cliente()
#IBAction func onGoButtonLH(_ sender: Any) {
let idTxt:String? = getText.text
if idTxt == "1234" {
self.performSegue(withIdentifier: "LoginToComercial", sender: self)
}else{
let urlString = "http://localhost:8080/RestServiceBgPrototype/cognitiva/clientService/"+idTxt!
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
//Implement JSON decoding and parsing
do {
let decoder = JSONDecoder()
self.cliente = try! decoder.decode(Cliente.self, from: data)
OperationQueue.main.addOperation{
self.performSegue(withIdentifier: "LoginToHome", sender: self.cliente)
}
}
}.resume()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "LoginToHome") {
let homeViewController = segue.destination as? HomeViewController
let cliente = sender as! Cliente
homeViewController?.cliente = cliente
}
}
}
HomeViewController.swift
class HomeViewController: UIViewController {
#IBOutlet weak var userLabel: UILabel!
var cliente = Cliente()
override func viewDidLoad() {
super.viewDidLoad()
let nombreCliente:String = cliente.nombre
let fullNameArr = nombreCliente.components(separatedBy:(" "))
let nombre = fullNameArr[2]
let apellido = fullNameArr[0]
self.userLabel.text = "Hola, "+nombre.capitalized+" "+apellido.capitalized
}
}
Any idea why I get this error?
To debug crash while it's happening and inspect what is the reason.
You can do this:
In your Breakpoint navigator at the bottom click plus button and add exception breakpoint
That will add to your project all exception break point.
It means when ever your app crashes is will stop on a line which generate crash.
Then we can figure out what to do next.
However, you are using force unwrap a lot, for instance:
let cliente = sender as! Cliente
if error != nil {
print(error!.localizedDescription)
}
It's better to do like this
if let error = error {
print(error.localizedDescription)
}
Please try not to use !. In case if your application encounter nil instead of object program will crash.
To answer your question. Your application do crash trying to send message getTextId to an object of type BanGuayaPrototype.ViewController.
This selector is not recognised. That's the root of your crash.
How did that happen?
For now what I can think. You have an object:
let obj: BanGuayaPrototype
and what are you trying to do is to call a method getTextId on this object.
This type of error is common in ObjectiveC. Occurs when you can try to send message to an object. If given object are unable to handle message program is crashing.

Resources