Synchronising data from Apple Watch to iPhone with Swift - ios

i am writing an Application for iOS and apple watch and need to synchronize data between apple watch and iPhone.
I did this for sending dat from iPhone to apple watch mentioned like here: http://telliott.io/2015/08/11/how-to-communicate-between-ios-and-watchos2.html
The other way, if i change data on my watch app and send the updated data to my iPhone there is a weird warning if the ViewController, where the message is received, is opened. When it is closed and i send the updated data from my watch there is no warning on my console and the data gets updated if i open the ViewController:
2015-11-16 11:28:19.057 GeoSocialRecommender[286:11448] This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.
Stack:(
0 CoreFoundation 0x0000000182410f60 <redacted> + 148
1 libobjc.A.dylib 0x0000000196fc3f80 objc_exception_throw + 56
2 CoreFoundation 0x0000000182410e90 <redacted> + 0
3 Foundation 0x000000018342f2d8 <redacted> + 88
4 Foundation 0x00000001832b5a1c <redacted> + 56
5 Foundation 0x00000001832b15dc <redacted> + 260
6 UIKit 0x0000000187aab8c4 <redacted> + 64
7 UIKit 0x0000000187aac3dc <redacted> + 244
8 UIKit 0x000000018820b1e4 <redacted> + 268
9 UIKit 0x0000000187cb0f10 <redacted> + 176
10 UIKit 0x000000018799f7ac <redacted> + 644
11 QuartzCore 0x000000018719eb58 <redacted> + 148
12 QuartzCore 0x0000000187199764 <redacted> + 292
13 QuartzCore 0x0000000187199624 <redacted> + 32
14 QuartzCore 0x0000000187198cc0 <redacted> + 252
15 QuartzCore 0x0000000187198a08 <redacted> + 512
16 QuartzCore 0x00000001871c7b0c <redacted> + 236
17 libsystem_pthread.dylib 0x00000001979f61e0 <redacted> + 584
18 libsystem_pthread.dylib 0x00000001979f5d58 <redacted> + 136
19 libsystem_pthread.dylib 0x00000001979f553c pthread_mutex_lock + 0
20 libsystem_pthread.dylib 0x00000001979f5020 start_wqthread + 4
)
Anyone can help me with this weird warning?
This is the method where i get the message
func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]){
if(WCSession.isSupported()){
self.prefs = Utils().importDataFromSession(prefs, applicationContext: applicationContext)
initializeGUI(true)
}
}

The WCSession header says:
/** ----------------------------- WCSessionDelegate -----------------------------
* The session calls the delegate methods when content is received and session
* state changes. All delegate methods will be called on the same queue. The
* delegate queue is a non-main serial queue. It is the client's responsibility
* to dispatch to another queue if neccessary.
*/
So if you want to update the UI you need to make sure that code runs on the application's main thread; so make the following change to your code and the warning will go away:
func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]){
if (WCSession.isSupported()) {
self.prefs = Utils().importDataFromSession(prefs, applicationContext: applicationContext)
dispatch_async(dispatch_get_main_queue(), {
initializeGUI(true)
})
}
}

Related

How can I diagnose and resolve a crash on WCSession sendMessage(_:replyHandler:errorHandler:)?

I'm building a watchOS app that needs to periodically request information from a companion iPhone app to refresh a complication.
To achieve this, I have a WKApplicationRefreshBackgroundTask that runs periodically. It uses sendMessage(_:replyHandler:errorHandler:) from WatchConnectivity to request the information from the iPhone app, process the reply, and update the complication.
This works reliably for many users most of the time, however, I’m seeing Apple Watch crashes in Xcode related to sendMessage(_:replyHandler:errorHandler:) and I worry this is leading to missed complication updates for users. Some users have been complaining about the complication not updating, so I'm trying to identify if there are issues outside of the regular limitations on how often a complication can refresh in watchOS.
Does anyone have any suggestions on how I can fix this issue? Or, do you have any suggestions for how I can better troubleshoot what's going wrong to cause the crash and figure out how to prevent it?
I've included a full example of one of the crashes at the bottom, along with the code that handles the background task and the code that handles sending and receiving values from the paired iPhone.
I’m never sending a message without a replyHandler, so while others have seen problems because the delegate method for a message without a handler was not implemented on iPhone, I don’t think that’s the issue here. To be safe I implemented the delegate method on iPhone as an empty method that does nothing.
UPDATE 30 January 2020: A friend suggested that maybe the issue is that the task is being marked complete by the 10 second timer while it's still in progress, causing a memory issue when something that's pending finishes, but wasn't sure what could be done about it. Maybe that's core to the issue here?
Here's my background refresh code from ExtensionDelegate:
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
for task in backgroundTasks {
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// set a timer in case it doesn't complete
// the maximum allowed is 15 seconds, and then it crashes, so schedule the new task and mark complete after 10
var timeoutTimer: Timer? = Timer.scheduledTimer(withTimeInterval: 10, repeats: false) { (timer) in
self.scheduleBackgroundRefresh()
backgroundTask.setTaskCompletedWithSnapshot(false)
}
// schedule the next refresh now in case the request crashes
scheduleBackgroundRefresh()
WatchConnectivityManager.shared.requestDataFromPhone()
ComplicationManager.shared.reloadComplication()
// as long as the expiration timer is valid, cancel the timer and set the task complete
// otherwise, we'll assume the timer has fired and the task has been marked complete already
// if it's marked complete again, that's a crash
if let timerValid = timeoutTimer?.isValid, timerValid == true {
timeoutTimer?.invalidate()
timeoutTimer = nil
backgroundTask.setTaskCompletedWithSnapshot(true)
}
default:
// make sure to complete unhandled task types
task.setTaskCompletedWithSnapshot(false)
}
}
}
private func scheduleBackgroundRefresh() {
let fiveMinutesFromNow: Date = Date(timeIntervalSinceNow: 5 * 60)
WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: fiveMinutesFromNow,
userInfo: nil) { (error) in
if let error = error {
fatalError("\(error)")
}
}
}
And here is WatchConnectivityManager:
import Foundation
import WatchKit
import WatchConnectivity
class WatchConnectivityManager: NSObject {
static let shared = WatchConnectivityManager()
let session = WCSession.default
private let receivedMessageQueue: OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
return queue
}()
private func process(messageOrUserInfo: [String : Any]) {
receivedMessageQueue.addOperation {
if let recievedValue = messageOrUserInfo["ValueFromPhone"] as? Int {
DispatchQueue.main.async {
ViewModel.shared.valueFromPhone = recievedValue
}
}
}
}
func requestDataFromPhone() {
if session.activationState == .activated {
let message: [String : Any] = ["Request" : true]
let replyHandler: (([String : Any]) -> Void) = { reply in
self.process(messageOrUserInfo: reply)
}
let errorHandler: ((Error) -> Void) = { error in
}
if session.isReachable {
session.sendMessage(message,
replyHandler: replyHandler,
errorHandler: errorHandler)
}
// send a request to the iPhone as a UserInfo in case the message fails
session.transferUserInfo(message)
}
}
}
extension WatchConnectivityManager: WCSessionDelegate {
func session(_ session: WCSession,
activationDidCompleteWith activationState: WCSessionActivationState,
error: Error?) {
if activationState == .activated {
requestDataFromPhone()
}
}
func session(_ session: WCSession,
didReceiveUserInfo userInfo: [String : Any])
{
process(messageOrUserInfo: userInfo)
}
}
Example crash:
Hardware Model: Watch3,4
AppVariant: 1:Watch3,4:6
Code Type: ARM (Native)
Role: Non UI
Parent Process: launchd [1]
OS Version: Watch OS 6.1.1 (17S449)
Release Type: User
Baseband Version: n/a
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x00000004
VM Region Info: 0x4 is not in any region. Bytes before following region: 638972
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
UNUSED SPACE AT START
--->
__TEXT 0009c000-000ac000 [ 64K] r-x/r-x SM=COW ...x/App Name
Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [377]
Triggered by Thread: 9
Thread 0 name:
Thread 0:
0 libsystem_kernel.dylib 0x4381f864 semaphore_wait_trap + 8
1 libdispatch.dylib 0x436dac26 _dispatch_sema4_wait + 12 (lock.c:139)
2 libdispatch.dylib 0x436db09a _dispatch_semaphore_wait_slow + 104 (semaphore.c:132)
3 FrontBoardServices 0x46de503e -[FBSSceneSnapshotRequestHandle performRequestForScene:] + 408 (FBSSceneSnapshotRequestHandle.m:67)
4 FrontBoardServices 0x46de96ac -[FBSSceneSnapshotAction snapshotRequest:performWithContext:] + 218 (FBSSceneSnapshotAction.m:168)
5 FrontBoardServices 0x46da4320 -[FBSSceneSnapshotRequest performSnapshotWithContext:] + 292 (FBSSceneSnapshotRequest.m:65)
6 UIKitCore 0x5ba6a000 __65-[UIApplication _performSnapshotsWithAction:forScene:completion:]_block_invoke_3 + 168 (UIApplication.m:7655)
7 FrontBoardServices 0x46de9568 -[FBSSceneSnapshotAction _executeNextRequest] + 244 (FBSSceneSnapshotAction.m:135)
8 FrontBoardServices 0x46de91e0 -[FBSSceneSnapshotAction executeRequestsWithHandler:completionHandler:expirationHandler:] + 244 (FBSSceneSnapshotAction.m:87)
9 UIKitCore 0x5ba69f20 __65-[UIApplication _performSnapshotsWithAction:forScene:completion:]_block_invoke_2 + 238 (UIApplication.m:7650)
10 UIKitCore 0x5ba69696 -[UIApplication _beginSnapshotSessionForScene:withSnapshotBlock:] + 772 (UIApplication.m:7582)
11 UIKitCore 0x5ba69e16 __65-[UIApplication _performSnapshotsWithAction:forScene:completion:]_block_invoke + 112 (UIApplication.m:7648)
12 UIKitCore 0x5b2c1110 -[UIScene _enableOverrideSettingsForActions:] + 40 (UIScene.m:1206)
13 UIKitCore 0x5b2c1330 -[UIScene _performSystemSnapshotWithActions:] + 112 (UIScene.m:1230)
14 UIKitCore 0x5ba69b90 -[UIApplication _performSnapshotsWithAction:forScene:completion:] + 382 (UIApplication.m:7647)
15 UIKitCore 0x5be89586 __98-[_UISceneSnapshotBSActionsHandler _respondToActions:forFBSScene:inUIScene:fromTransitionCont... + 146 (_UISceneSnapshotBSActionsHandler.m:54)
16 UIKitCore 0x5ba68fd4 _runAfterCACommitDeferredBlocks + 274 (UIApplication.m:3038)
17 UIKitCore 0x5ba5b3da _cleanUpAfterCAFlushAndRunDeferredBlocks + 198 (UIApplication.m:3016)
18 UIKitCore 0x5ba82702 _afterCACommitHandler + 56 (UIApplication.m:3068)
19 CoreFoundation 0x43b63644 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 18 (CFRunLoop.c:1758)
20 CoreFoundation 0x43b5f43c __CFRunLoopDoObservers + 350 (CFRunLoop.c:1868)
21 CoreFoundation 0x43b5f956 __CFRunLoopRun + 1150 (CFRunLoop.c:2910)
22 CoreFoundation 0x43b5f23a CFRunLoopRunSpecific + 370 (CFRunLoop.c:3192)
23 GraphicsServices 0x46973cd0 GSEventRunModal + 96 (GSEvent.c:2246)
24 UIKitCore 0x5ba61580 UIApplicationMain + 1730 (UIApplication.m:4773)
25 libxpc.dylib 0x438fbcf0 _xpc_objc_main.cold.3 + 152
26 libxpc.dylib 0x438eca34 _xpc_objc_main + 184 (main.m:126)
27 libxpc.dylib 0x438ee934 xpc_main + 110 (init.c:1568)
28 Foundation 0x443f3156 -[NSXPCListener resume] + 172 (NSXPCListener.m:276)
29 PlugInKit 0x4b58b26c -[PKService run] + 384 (PKService.m:165)
30 WatchKit 0x52e9dafe WKExtensionMain + 62 (main.m:19)
31 libdyld.dylib 0x43715e82 start + 2
Thread 1 name:
Thread 1:
0 libsystem_kernel.dylib 0x4381f814 mach_msg_trap + 20
1 libsystem_kernel.dylib 0x4381eece mach_msg + 42 (mach_msg.c:103)
2 CoreFoundation 0x43b63946 __CFRunLoopServiceMachPort + 152 (CFRunLoop.c:2575)
3 CoreFoundation 0x43b5f9de __CFRunLoopRun + 1286 (CFRunLoop.c:2931)
4 CoreFoundation 0x43b5f23a CFRunLoopRunSpecific + 370 (CFRunLoop.c:3192)
5 Foundation 0x443bf398 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 180 (NSRunLoop.m:374)
6 Foundation 0x443bf2b4 -[NSRunLoop(NSRunLoop) runUntilDate:] + 76 (NSRunLoop.m:421)
7 UIKitCore 0x5badf012 -[UIEventFetcher threadMain] + 140 (UIEventFetcher.m:637)
8 Foundation 0x444c1b60 __NSThread__start__ + 708 (NSThread.m:724)
9 libsystem_pthread.dylib 0x438ad1ac _pthread_start + 130 (pthread.c:896)
10 libsystem_pthread.dylib 0x438b3f28 thread_start + 20
Thread 2 name:
Thread 2:
0 libsystem_kernel.dylib 0x43836d04 __psynch_cvwait + 24
1 libsystem_pthread.dylib 0x438b02c2 _pthread_cond_wait + 496 (pthread_cond.c:591)
2 libsystem_pthread.dylib 0x438aca4a pthread_cond_wait + 38 (pthread_cancelable.c:558)
3 Foundation 0x444381f0 -[NSOperation waitUntilFinished] + 446 (NSOperation.m:737)
4 Foundation 0x444a5302 __NSOPERATIONQUEUE_IS_WAITING_ON_AN_OPERATION__ + 22 (NSOperation.m:2610)
5 Foundation 0x444222ee -[NSOperationQueue addOperations:waitUntilFinished:] + 128 (NSOperation.m:2618)
6 WatchConnectivity 0x53f9871e __47-[WCSession handleUserInfoResultWithPairingID:]_block_invoke.491 + 540 (WCSession.m:1440)
7 WatchConnectivity 0x53fa5608 -[WCFileStorage enumerateUserInfoResultsWithBlock:] + 1564 (WCFileStorage.m:505)
8 WatchConnectivity 0x53f984ca __47-[WCSession handleUserInfoResultWithPairingID:]_block_invoke_2 + 284 (WCSession.m:1430)
9 Foundation 0x444a4794 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 10 (NSOperation.m:1541)
10 Foundation 0x443d2f7a -[NSBlockOperation main] + 74 (NSOperation.m:1560)
11 Foundation 0x444a63e2 __NSOPERATION_IS_INVOKING_MAIN__ + 22 (NSOperation.m:2184)
12 Foundation 0x443d2b96 -[NSOperation start] + 578 (NSOperation.m:2201)
13 Foundation 0x444a6b7c __NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION__ + 22 (NSOperation.m:2215)
14 Foundation 0x444a6798 __NSOQSchedule_f + 134 (NSOperation.m:2226)
15 libdispatch.dylib 0x436d9846 _dispatch_call_block_and_release + 10 (init.c:1408)
16 libdispatch.dylib 0x436da8b8 _dispatch_client_callout + 6 (object.m:495)
17 libdispatch.dylib 0x436dc6f8 _dispatch_continuation_pop + 330 (inline_internal.h:2484)
18 libdispatch.dylib 0x436dc08c _dispatch_async_redirect_invoke + 520 (queue.c:803)
19 libdispatch.dylib 0x436e6eac _dispatch_root_queue_drain + 540 (inline_internal.h:2525)
20 libdispatch.dylib 0x436e73e0 _dispatch_worker_thread2 + 98 (queue.c:6628)
21 libsystem_pthread.dylib 0x438aecd2 _pthread_wqthread + 158 (pthread.c:2364)
22 libsystem_pthread.dylib 0x438b3f10 start_wqthread + 20
Thread 3:
0 libsystem_pthread.dylib 0x438b3efc start_wqthread + 0
Thread 4:
0 libsystem_pthread.dylib 0x438b3efc start_wqthread + 0
Thread 5:
0 libsystem_pthread.dylib 0x438b3efc start_wqthread + 0
Thread 6 name:
Thread 6:
0 libsystem_kernel.dylib 0x43838c6c kevent_qos + 24
1 libdispatch.dylib 0x436f2b74 _dispatch_kq_poll + 204 (event_kevent.c:736)
2 libdispatch.dylib 0x436f280a _dispatch_kq_drain + 96 (event_kevent.c:809)
3 libdispatch.dylib 0x436f2196 _dispatch_event_loop_poke + 162 (event_kevent.c:1918)
4 libdispatch.dylib 0x436e32b8 _dispatch_mgr_queue_push + 110 (queue.c:5857)
5 WatchConnectivity 0x53f9aa26 -[WCSession createAndStartTimerOnWorkQueueWithHandler:] + 150 (WCSession.m:1803)
6 WatchConnectivity 0x53f90790 -[WCSession onqueue_sendMessageData:replyHandler:errorHandler:dictionaryMessage:] + 382 (WCSession.m:674)
7 WatchConnectivity 0x53f901da __51-[WCSession sendMessage:replyHandler:errorHandler:]_block_invoke.256 + 190 (WCSession.m:630)
8 Foundation 0x444a4794 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 10 (NSOperation.m:1541)
9 Foundation 0x443d2f7a -[NSBlockOperation main] + 74 (NSOperation.m:1560)
10 Foundation 0x444a63e2 __NSOPERATION_IS_INVOKING_MAIN__ + 22 (NSOperation.m:2184)
11 Foundation 0x443d2b96 -[NSOperation start] + 578 (NSOperation.m:2201)
12 Foundation 0x444a6b7c __NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION__ + 22 (NSOperation.m:2215)
13 Foundation 0x444a6798 __NSOQSchedule_f + 134 (NSOperation.m:2226)
14 libdispatch.dylib 0x436e4c02 _dispatch_block_async_invoke2 + 80 (queue.c:525)
15 libdispatch.dylib 0x436da8b8 _dispatch_client_callout + 6 (object.m:495)
16 libdispatch.dylib 0x436dc6f8 _dispatch_continuation_pop + 330 (inline_internal.h:2484)
17 libdispatch.dylib 0x436dc08c _dispatch_async_redirect_invoke + 520 (queue.c:803)
18 libdispatch.dylib 0x436e6eac _dispatch_root_queue_drain + 540 (inline_internal.h:2525)
19 libdispatch.dylib 0x436e73e0 _dispatch_worker_thread2 + 98 (queue.c:6628)
20 libsystem_pthread.dylib 0x438aecd2 _pthread_wqthread + 158 (pthread.c:2364)
21 libsystem_pthread.dylib 0x438b3f10 start_wqthread + 20
Thread 7:
0 libsystem_pthread.dylib 0x438b3efc start_wqthread + 0
Thread 8:
0 libsystem_pthread.dylib 0x438b3efc start_wqthread + 0
Thread 9 name:
Thread 9 Crashed:
0 libdispatch.dylib 0x436eacec dispatch_channel_cancel + 6 (source.c:1020)
1 WatchConnectivity 0x53f909c6 __81-[WCSession onqueue_sendMessageData:replyHandler:errorHandler:dictionaryMessage:]_block_invoke + 42 (WCSession.m:675)
2 libdispatch.dylib 0x436da8b8 _dispatch_client_callout + 6 (object.m:495)
3 libdispatch.dylib 0x436dc6f8 _dispatch_continuation_pop + 330 (inline_internal.h:2484)
4 libdispatch.dylib 0x436ea81e _dispatch_source_invoke + 1758 (source.c:568)
5 libdispatch.dylib 0x436e6eac _dispatch_root_queue_drain + 540 (inline_internal.h:2525)
6 libdispatch.dylib 0x436e73e0 _dispatch_worker_thread2 + 98 (queue.c:6628)
7 libsystem_pthread.dylib 0x438aecd2 _pthread_wqthread + 158 (pthread.c:2364)
8 libsystem_pthread.dylib 0x438b3f10 start_wqthread + 20
Thread 10:
0 libsystem_pthread.dylib 0x438b3efc start_wqthread + 0
Thread 11:
0 libsystem_pthread.dylib 0x438b3efc start_wqthread + 0
Thread 9 crashed with ARM Thread State (32-bit):
r0: 0x00000000 r1: 0x80000000 r2: 0x00000001 r3: 0x7fffffff
r4: 0x16548f40 r5: 0x00000000 r6: 0x00000110 r7: 0x3f057e58
r8: 0x00000000 r9: 0x00000000 r10: 0x00000000 r11: 0x00401600
ip: 0x66e39628 sp: 0x3f057e30 lr: 0x53f909c7 pc: 0x436eacec
cpsr: 0x80000030
I assume your friend is right:
When you set your background task as complete, the system will suspend your app, see here.
And the system can purge suspended apps without warning, see here.
So if this happens, replyHandler or errorHandler cannot be called, and the app crashes.
You can therefore not rely on sendMessage to wake up the iOS app and to call replyHandler in time.
I suggest that you initialize the transfer of complication data on iOS. To do so regularly, you could use silent push notifications that wake up your iOS app, and send new complication data using transferCurrentComplicationUserInfo(_:)see here. This userInfo is received even if your watch app is not running, and the complication data can be updated as required.
EDIT:
While my solution above might work, there might be a much simpler solution:
Maybe it is not required to update your ViewModel in respond to sendMessage, only the complications. If so, you could simply use sendMessage with replyHandler and errorHandler set to nil.
sendMessage is guaranteed to wake up the iOS app in the future, even when the watchOS app is already inactive. The iOS app could then send complication data, and these would be displayed immediately.
Additionally, the iOS app could send the userInfo that updates your ViewModel as application context. It would then be available when the watchOS app becomes active again, and you can update the ViewModel.
If this fits to your use case, you could simply remove the timer and complete the background task immediately after sendMessage.

CMotionManager crash on instantiation

EDIT: This appears to be resolved on iOS 13. Leaving all the original details below.
I'm getting a crash when instantiating my CMMotionManager object for Core Motion. This is on an iPhone Xs running iOS 12.0.1.
I can reliably reproduce this with a single-view app, with the following view controller.
import UIKit
import CoreMotion
class ViewController: UIViewController {
var motion: CMMotionManager?
override func viewDidLoad() {
super.viewDidLoad()
// This causes a crash on iPhone Xs, iOS 12.0.1
self.motion = CMMotionManager()
}
}
Full sample project is at https://github.com/doctorcolinsmith/motiontestcrash/tree/master
When running the above, I am getting a fault on a thread with the following output in the debugger.
=================================================================
Main Thread Checker: UI API called on a background thread: -[UIApplication applicationState]
PID: 3634, TID: 630341, Thread name: com.apple.CoreMotion.MotionThread, Queue name: com.apple.root.default-qos.overcommit, QoS: 0
Backtrace:
4 libobjc.A.dylib 0x000000019b0d3894 <redacted> + 56
5 CoreMotion 0x00000001a19337a4 CoreMotion + 305060
6 CoreMotion 0x00000001a1933cd8 CoreMotion + 306392
7 CoreMotion 0x00000001a1933be8 CoreMotion + 306152
8 CoreMotion 0x00000001a19653cc CoreMotion + 508876
9 CoreMotion 0x00000001a196542c CoreMotion + 508972
10 CoreFoundation 0x000000019be6c888 <redacted> + 28
11 CoreFoundation 0x000000019be6c16c <redacted> + 276
12 CoreFoundation 0x000000019be67470 <redacted> + 2324
13 CoreFoundation 0x000000019be66844 CFRunLoopRunSpecific + 452
14 CoreFoundation 0x000000019be675a8 CFRunLoopRun + 84
15 CoreMotion 0x00000001a1964d64 CoreMotion + 507236
16 libsystem_pthread.dylib 0x000000019bae1a04 <redacted> + 132
17 libsystem_pthread.dylib 0x000000019bae1960 _pthread_start + 52
18 libsystem_pthread.dylib 0x000000019bae9df4 thread_start + 4
2018-10-24 16:19:31.423680-0700 motiontest[3634:630341] [reports] Main Thread Checker: UI API called on a background thread: -[UIApplication applicationState]
PID: 3634, TID: 630341, Thread name: com.apple.CoreMotion.MotionThread, Queue name: com.apple.root.default-qos.overcommit, QoS: 0
Backtrace:
4 libobjc.A.dylib 0x000000019b0d3894 <redacted> + 56
5 CoreMotion 0x00000001a19337a4 CoreMotion + 305060
6 CoreMotion 0x00000001a1933cd8 CoreMotion + 306392
7 CoreMotion 0x00000001a1933be8 CoreMotion + 306152
8 CoreMotion 0x00000001a19653cc CoreMotion + 508876
9 CoreMotion 0x00000001a196542c CoreMotion + 508972
10 CoreFoundation 0x000000019be6c888 <redacted> + 28
11 CoreFoundation 0x000000019be6c16c <redacted> + 276
12 CoreFoundation 0x000000019be67470 <redacted> + 2324
13 CoreFoundation 0x000000019be66844 CFRunLoopRunSpecific + 452
14 CoreFoundation 0x000000019be675a8 CFRunLoopRun + 84
15 CoreMotion 0x00000001a1964d64 CoreMotion + 507236
16 libsystem_pthread.dylib 0x000000019bae1a04 <redacted> + 132
17 libsystem_pthread.dylib 0x000000019bae1960 _pthread_start + 52
18 libsystem_pthread.dylib 0x000000019bae9df4 thread_start + 4
(lldb)
Has anyone encountered this before or have an idea on how to solve the crash?
Well, I've tested your application both physical iPhone 6S and iPhone 7 - obviously with iOS 12.0.1. I've also checked for a couple of things in your project and couldn't reproduce your problem at all - not even in simulators - and I don't think it's possible to download a simulator with specific fixes (12.0.x), only with minor version updates - so 12.1 being the next one. This looks really specific on iPhone XS hardware, and I would suggest you to fill an issue with Apple support.
EDIT: Well, I saw that you've already filled a bug report on openradar. This guy even referenced the bug report status on openradar-mirror.
I don't know much about CoreMotion, but the error message tells you you're trying to call a UI action on a background thread. Try putting your code into:
DispatchQueue.main.async {
//your code here
}
It also seems you're trying to do UI related actions in viewDidLoad(). Technically that's fine, but remember that some views probably aren't layed out at that point in time.

ios exception analyse NSInternalInconsistencyException

My app crash with a NSInternalInconsistencyException like this
Exception reason:NSInternalInconsistencyException
Exception name:Can't cancel on a touch that isn't already active!
Exception stack:(
0 CoreFoundation 0x0000000191a4d1d0 <redacted> + 148
1 libobjc.A.dylib 0x000000019048455c objc_exception_throw + 56
2 CoreFoundation 0x0000000191a4d08c <redacted> + 0
3 Foundation 0x000000019250502c <redacted> + 112
4 UIKit 0x0000000197fd1960 <redacted> + 404
5 UIKit 0x0000000197fcf970 <redacted> + 1648
6 libdispatch.dylib 0x00000001908d61fc <redacted> + 24
7 libdispatch.dylib 0x00000001908d61bc <redacted> + 16
8 libdispatch.dylib 0x00000001908e43dc <redacted> + 928
9 libdispatch.dylib 0x00000001908d99a4 <redacted> + 652
10 libdispatch.dylib 0x00000001908e634c <redacted> + 572
11 libdispatch.dylib 0x00000001908e60ac <redacted> + 124
12 libsystem_pthread.dylib 0x0000000190adf2a0 _pthread_wqthread + 1288
13 libsystem_pthread.dylib 0x0000000190aded8c start_wqthread + 4
)
How do i analyse the log? Like What do those number tags mean,"+ 148" "+ 56"...? How to detect the code that have invoked this exception.
Is this a crash from a release build of the app, or do you have it in Xcode? If in Xcode please provide the code causing the crash?
Looking at your report, the line
Can't cancel on a touch that isn't already active!
seems very telling. I would look through your code for anywhere you are interacting with a UITouch object, or perhaps a UIGestureRecognizer. My guess would be that somewhere you are manually calling to cancel an interaction that you should not be, and there is a race condition where that can sometimes happen after the system has already cancelled the touch (or vice versa, I guess).

Firebase App configuration crash

I have a custom keyboard for iOS that uses Firebase for analytics. The Firebase app configuration is done at the initializer with a dispatch_once clause with the token as a global variable.
var token: dispatch_once_t = 0
class KeyboardViewController: UIInputViewController {
// ..
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
dispatch_once(&token) {
FIRApp.configure()
} // line 90
}
// ..
}
This is working fine but I am receiving many crash reports that indicate crashes on many devices when the app is configured. I am stuck for days trying to figure out the cause. Here is a part of one of the crash reports stack trace:
Exception Type: EXC_CRASH (SIGQUIT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Termination Signal: Quit: 3
Termination Reason: Namespace SIGNAL, Code 0x3
Terminating Process: launchd [1]
Triggered by Thread: 0
Thread 0 name:
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x000000018fab6338 __semwait_signal_nocancel + 8
1 libsystem_c.dylib 0x000000018f9e20dc nanosleep$NOCANCEL + 200 (nanosleep.c:104)
2 libsystem_c.dylib 0x000000018fa0568c sleep$NOCANCEL + 44 (sleep.c:62)
3 libsystem_dnssd.dylib 0x000000018fa6e7d4 ConnectToServer + 832 (dnssd_clientstub.c:607)
4 libsystem_dnssd.dylib 0x000000018fa6ff44 DNSServiceCreateConnection + 76 (dnssd_clientstub.c:1785)
5 libsystem_network.dylib 0x000000018fb2d318 __nw_resolver_set_update_handler_block_invoke + 872 (resolver.m:1031)
6 libdispatch.dylib 0x000000018f9711c0 _dispatch_client_callout + 16 (object.m:455)
7 libdispatch.dylib 0x000000018f97e860 _dispatch_barrier_sync_f_invoke + 84 (queue.c:3457)
8 libsystem_network.dylib 0x000000018fb2ce78 nw_resolver_set_update_handler + 208 (resolver.m:1275)
9 SystemConfiguration 0x0000000190f8a16c __SCNetworkReachabilityRestartResolver + 260 (SCNetworkReachability.c:1711)
10 SystemConfiguration 0x0000000190f891c8 __SCNetworkReachabilitySetDispatchQueue + 764 (SCNetworkReachability.c:1823)
11 SystemConfiguration 0x0000000190f88ccc SCNetworkReachabilityScheduleWithRunLoop + 504 (SCNetworkReachability.c:1586)
12 CustomKeyboard 0x000000010013f630 -[FIRReachabilityChecker start] + 196
13 CustomKeyboard 0x000000010013abac -[FIRNetwork init] + 156
14 CustomKeyboard 0x0000000100132e28 -[FIRClearcutLogger init] + 416
15 CustomKeyboard 0x0000000100132c68 __35+[FIRClearcutLogger sharedInstance]_block_invoke + 36
16 libdispatch.dylib 0x000000018f9711c0 _dispatch_client_callout + 16 (object.m:455)
17 libdispatch.dylib 0x000000018f971fb4 dispatch_once_f + 56 (once.c:57)
18 CustomKeyboard 0x0000000100132c40 +[FIRClearcutLogger sharedInstance] + 108
19 CustomKeyboard 0x0000000100137214 +[FIRApp initClearcut] + 60
20 CustomKeyboard 0x0000000100136688 +[FIRApp configureDefaultAppWithOptions:sendingNotifications:] + 132
21 CustomKeyboard 0x000000010013643c +[FIRApp configure] + 316
22 libdispatch.dylib 0x000000018f9711c0 _dispatch_client_callout + 16 (object.m:455)
23 libdispatch.dylib 0x000000018f971fb4 dispatch_once_f + 56 (once.c:57)
24 CustomKeyboard 0x00000001000e314c _TFC19CustomKeyboard22KeyboardViewControllercfT7nibNameGSqSS_6bundleGSqCSo8NSBundle__S0_ + 1500 (KeyboardViewController.swift:90)
25 CustomKeyboard 0x00000001000e3270 _TToFC19CustomKeyboard22KeyboardViewControllercfT7nibNameGSqSS_6bundleGSqCSo8NSBundle__S0_ + 112 (KeyboardViewController.swift:0)
26 UIKit 0x00000001971f7688 -[_UIViewServiceViewControllerOperator __createViewController:withContextToken:fbsDisplays:appearanceSerializedRepresentations:legacyAppearance:traitCollection:initialInterfaceOrientation:hostAccessibilityServerPort:canShowTextServices:replyHandler:] + 2216 (UIViewServiceViewControllerOperator.m:1732)
27 CoreFoundation 0x0000000190aee160 __invoking___ + 144
28 CoreFoundation 0x00000001909e1c3c -[NSInvocation invoke] + 284 (NSForwarding.m:2948)
29 CoreFoundation 0x00000001909e66ec -[NSInvocation invokeWithTarget:] + 60 (NSForwarding.m:3019)
Apparently, the call trace after calling FIRApp.configure() is going through system libraries.
One observation from the stack trace is that the crash has something to do with checking the reachability of the device. However, I tried to reproduce a scenario where there is no internet connection but it's working fine.
Please note that all the crashes are happening on iOS 10 and most of them on iPhone 6.
Any help to figure out the cause of the crashes would be appreciated.
It is not recommended to use Firebase Analytics in an extension as the SDK does not support extension well. App extensions have limited functionalities compared to a full app so Firebase Analytics may not work well under some conditions, like the network in this case. The team is looking into supporting extensions better later.
It seems like the network is not available on custom keyboard as stated by Apple
"By default, a keyboard has no network access and cannot share a
container with its containing app. To enable these things, set the
value of the RequestsOpenAccess Boolean key in the Info.plist file to
YES. Doing this expands the keyboard’s sandbox, as described in
Designing for User Trust."
https://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/CustomKeyboard.html#//apple_ref/doc/uid/TP40014214-CH16-SW1

iOS9 'modifying the autolayout engine from a background thread' without using autolayout

I started getting this warning :
This application is modifying the autolayout engine from a background
thread, which can lead to engine corruption and weird crashes. This
will cause an exception in a future release.
Here is the backtrace with the warning message :
Stack:(
0 CoreFoundation 0x25542303 <redacted> + 150
1 libobjc.A.dylib 0x24d0edff objc_exception_throw + 38
2 CoreFoundation 0x25542231 <redacted> + 0
3 Foundation 0x25e25bbb <redacted> + 170
4 Foundation 0x25ccb637 <redacted> + 38
5 UIKit 0x297e0431 <redacted> + 52
6 UIKit 0x297e0e1f <redacted> + 222
7 UIKit 0x297fd52d <redacted> + 96
8 UIKit 0x29efe579 <redacted> + 320
9 UIKit 0x299dc8e9 <redacted> + 148
10 UIKit 0x299cb44f <redacted> + 42
11 UIKit 0x296d5a83 <redacted> + 714
12 QuartzCore 0x277b1ad5 <redacted> + 128
13 QuartzCore 0x277ad1d1 <redacted> + 352
14 QuartzCore 0x277ad061 <redacted> + 16
15 QuartzCore 0x277ac581 <redacted> + 368
16 QuartzCore 0x277ac233 <redacted> + 614
17 QuartzCore 0x277d9b63 <redacted> + 310
18 libsystem_pthread.dylib 0x25279905 <redacted> + 508
19 libsystem_pthread.dylib 0x25279507 <redacted> + 86
20 libsystem_pthread.dylib 0x2527a485 pthread_exit + 28
21 Foundation 0x25ca31d7 <redacted> + 10
22 Foundation 0x25d5e34f <redacted> + 1178
23 libsystem_pthread.dylib 0x2527ac7f <redacted> + 138
24 libsystem_pthread.dylib 0x2527abf3 _pthread_start + 110
25 libsystem_pthread.dylib 0x25278a08 thread_start + 8
As far as i know i don't use Autolayout (as i want the app to be iOS 5.1.1 compatible). and also i don't seem to be within the reported backtrace.
I also have the PSPDFUIKitMainThreadGuard class enabled, which should be checking the main thread accesses but nothing trigered out of this thing.
Is there any way how to find out what is doing such a thing?
Question This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes doesn't explain how to debug such thing.
Whether or not you are using Autolayout directly is not the issue at hand. The OS is converting legacy autoresizingMask to modern NSLayoutConstraint under the hood.
The issue has to do with modifying the UI from anywhere but the main tread.
This typically happens when:
responding to a NSNotification
returning from an async method
executing a completion block on a thread you do not control
explicitly scheduling a task in the background
Note about The app doesn't crash...
The app will crash. All you need is time and a few thousand users...

Resources