iOS 10 with XCode 8 GM caused NSUserDefaults to intermittently not work - ios

NOTE: I have seen many other posts on Stack Overflow about NSUserDefaults being renamed to UserDefaults in Swift or not working on simulator until a restart. This is not a duplicate by anyway. Many of the questions SO is tagging against is from 4 years ago. My question is specific to iOS 10 from this year as this has always worked in older versions. I have mentioned in my question already that my question is not a duplicate of those questions as those were simulator bugs in swift and my issue is on device objective C bug. Please read the questions before marking as duplicate
My issue is different as I am able to reproduce this on objective C and on physical device itself.
I created a brand new project from scratch for this test. I placed this code in the viewDidLoad of a view controller:
if (![[NSUserDefaults standardUserDefaults] valueForKey:#"checkIfInitialized"]){
NSLog(#"setting checkIfInitialized as not exist");
[[NSUserDefaults standardUserDefaults] setValue:#"test" forKey:#"checkIfInitialized"];
[[NSUserDefaults standardUserDefaults] synchronize];
self.view.backgroundColor=[UIColor redColor];
self.mylabel.text=#"NSUserDefaults was NOT there, try running again";
} else {
NSLog(#"checkIfInitialized exists already");
self.view.backgroundColor=[UIColor blueColor];
self.mylabel.text=#"NSUserDefaults was already there this time, try running again";
}
Now if I run the app about 10 times, few times it finds the checkIfInitialized and sometimes it doesn't. No exact number on how many times it fails as it might work 3 times then fail next 2 times then work 4 times and fail once and so on.
Now something I have noticed (not 100% sure though) that the issue only seems to happen when I am testing connected via Xcode. If I run by launching the app by clicking the app icon on device without Xcode, then it seems to work fine but I can't be 100% sure.
I noticed this error occur sometimes:
[User Defaults] Failed to write value for key checkIfInitialized in CFPrefsPlistSource<0x1700f7200> (Domain: com.xxxx.appname, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null)): Path not accessible, switching to read-only
I have this very simple project on my dropbox if you want to test it out.
I would suggest testing about 10-15 times to reproduce this issue.
https://www.dropbox.com/s/j7vbgl6e15s57ix/nsuserdefaultbug.zip?dl=0
This works completely fine on iOS 9 so definitely something to do with iOS 10.
EDIT
Bug logged: 28287988
Response from apple DTS team:
First off, you should first determine whether standardUserDefaults or
valueForKey is failing. My guess is that “standardUserDefaults” is
returning NULL and, if that’s the case, then that’s something you
should be guarding against generally. Notably, standardUserDefaults
will return NULL if the preference file is encrypted in the
environment the app is currently running in (for example, preferences
is set to “NSFileProtectionComplete” and the app is running in the
background). That shouldn’t be an issue for standard foreground-only
apps, but it’s something to be aware of anyway.
It’s very likely that Xcode is actually inducing the problem here.
Xcode vastly complicates the app launching environment in a way that’s
VERY different than a standard app launch. My guess is that this is
basically being triggered by Xcode’s timing inducing an an expected
situation during the app launch, but if you want a more formal test of
that try setting a single breakpoint in applicationDidFinishLaunching
and continuing in the debugger as soon as you hit it. My guess is
just adding that disrupts the timing enough to stop the problem from
happening. Sort of. It’s iOS 10 only in the sense that iOS 9 will
never print that log message, but that’s because the log message was
added in iOS 10. The code itself is similar enough to iOS 9.3 that I
suspect exactly the same behavior is (at least in theory) possible in
iOS 9.

Yes, this is definitely a reproducible bug.
It happens with the GM release of Xcode 8 and iOS 10.
It is not the linked question referring to Swift.
It is not the linked question referring to beta versions of the Simulator.
The bug happens on devices and on the Simulator. It is intermittent: saving will work six times and then fail. Unlike you, I did not get the "failed to write key" message.
The bug also occurs when operating directly on the device without Xcode. This is in fact how I discovered it.
You should report a bug to Apple, especially since you have a short program that will reproduce it. I will do the same.
One key difference: In my case the failure is in writing the default. The previously written value remains in NSUserDefaults. Sometimes one key is successfully written while another is unchanged.

A similarly very intelligent DTS response from my own support request. Basically, killing using Xcode is more murderous than anything that would naturally happen on the device (even the double-Home-click-and-upswipe method) and since everything is abruptly crashed when Xcode halts it, the lazy writing of NSUserDefaults can fail, or be only half completed.
And indeed, pure on-device testing of the app, without Xcode involved, shows that everything does get correctly written to NSUserDefaults when the app is terminated.
I have closed my own bug report.

Related

iOS crash below iOS9.3 with SIGSEGV, different Crash Log

Many crashes happened below the iOS9.3 (which means devices with iOS10 are OK)..
The crash logs seem to show that it's not a problem about API that can only be used below iOS 9.3 .
But I have no idea about the crash logs. ( I'm sorry ...for I just start to study iOS development for only 2 month )
Could you please help me analyze the crash logs ?
Really Thanks !
crash log 1
crash log 2
AXE_BAD_ACCESS - this is problem with memory. One of function tried to use variable which already released. I think you need to check use your TableView and cells for this table.
Also to find problem with memory you can try to use zombies
Used to have the similar strange crashes in my app. And only in production, when testing from TestFlight. Building on device with ios 9 caused no problems.
Maybe it sounds strange, but try to convert all images you use in app to images with included sRGB color profile. For me it helped.

EXC_BAD_ACCESS(Code=EXC_ARM_DA_ALIGN) Only when running app on device from Xcode

I'm getting a really weird EXC_BAD_ACCESS(Code=EXC_ARM_DA_ALIGN) crash on my app which is written in swift but only when i run it on a 32 bit device and only if its running from Xcode (the device is still hooked to Xcode), If i start the app without Xcode it runs fine. I can't give any code since no matter what i do i get no stack trace or anything like that .Only the mention error on the AppDelegate, even though the crash is in different screens further in the app (crashes on second screen).
Any idea as to why the crash would happen only when Xcode is running the app
You are using some variable or object which is yet to be initialised. Please review your code and you will get the error. You can add exceptional break point to get the actual position of the error.
It's a memory alignment issue. Search on EXC_ARM_DA_ALIGN.
https://brewx.qualcomm.com/bws/content/gi/common/appseng/en/knowledgebase/docs/kb95.html
use memcpy
char*Code; int pc;
double f;
memcpy(Code+pc, &f, sizeof(f)); // instead of *(double*)(Code+pc)=f; that generates EXC_ARM_DA_ALIGN

iOS Keychain writing value results in error code -34018

I have an iOS application that stores some sensitive information in the keychain.
While writing values into the keychain, I am getting error code -34018.
I am currently using Apple's iOS KeyChainItemWrapper class.
Both of the following lines of code receive the same error code.
OSStatus res1 = SecItemCopyMatching((__bridge CFDictionaryRef)genericPasswordQuery, (CFTypeRef *)&attributes);
OSStatus res = SecItemUpdate((__bridge CFDictionaryRef)updateItem, (__bridge CFDictionaryRef)tempCheck);
This issue does not occur every time, but intermittently. Once I get this error, I am no longer able to write any values to the keychain.
I have printed the error description like so:
NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:res userInfo:nil];
and this is what the error prints out:
Error: Error Domain=NSOSStatusErrorDomain Code=-34018 "The operation couldn’t be completed. (OSStatus error -34018.)"
Seems like this is a bug in Keychain, which only appears when you launch your app from xcode. See here: https://github.com/soffes/sskeychain/issues/52
We debugged it a lot and it seems an issue accessing the keychain when
the app is launched from the background. This is only happening with
the debugger (i.e. when launched from Xcode). We think the issue
might be related in our case to the debugger keeping alive the app
even if it should be killed by the OS. We tried in fact to run the
app and then put it in background and launch many other app to occupy
RAM. With the debugger the bug came up when resuming the app from the
background, while without the debugger it didn't (we did run at least
10 tests each).
If someone will come here back with this error and XCode8 with iOS10, probably you have to enable KeyChain Share in the tab Capabilities:
As others have mentioned, this is a Keychain bug, one that Apple is aware of and has been aware of since at least mid-2015.
As of March 22, 2016, however, Apple has said:
We believe these problems were resolved in iOS 9.3.
iOS 9.3 was released on March 21, 2016.
See the thread: https://forums.developer.apple.com/thread/4743
To quote the response by an Apple employee:
Mar 22, 2016 3:28 AM
OK, here’s the latest. This is a complex problem with multiple possible causes:
Some instances of the problem are caused by incorrect app signing. You can easily distinguish this case because the problem is 100% reproducible.
Some instances of the problem are caused by a bug in how iOS supports app development (r. 23,991,853). Debugging this was complicated by the fact that another bug in the OS (r. 23,770,418) masked its effect, meaning the problem only cropped up when the device was under memory pressure.
We believe these problems were resolved in iOS 9.3.
We suspect that there may be yet more causes of this problem.
So, if you see this problem on a user device (one that hasn’t been talked to by Xcode) that’s running iOS 9.3 or later, please do file a bug report about it. Try to include the device system log in your bug report (I realise that can be tricky when dealing with customer devices; one option is to ask the customer to install Apple Configurator, which lets them view the system log). And if you do file a bug, please post your bug number, just for the record.
On behalf of Apple I’d like to thank everyone for their efforts in helping to track down this rather horrid issue.
Share and Enjoy
This held me up for 2 hours before I found a quick "fix" - reboot the iOS device
A quote from the discussion at http://forums.developer.apple.com/thread/4743,
From user littledetails
As others have reported, this mysterious keychain error is most easily observable when launching via Xcode with the debugger attached. Once the error starts occurring, the keychain doesn't seem to right itself regardless of memory pressure until one reboots the device.
When I rebooted my device the error went away, allowing me to continue testing. Not sure what else to do. In my situation, moving to NSUserDefaults or some other storage solution was not a possibility.
One way to get around this issue with the keychain is to use dispatch_async to allow the app to launch. This works when the app is opened from the background. Also make sure you have the kSecAttrAccessibleAfterFirstUnlock accessibility setting on the keychain.
dispatch_async(dispatch_get_main_queue(), ^{
// save/write to keychain
})
I am using GenericKeychain classes from apple:
https://developer.apple.com/library/content/samplecode/GenericKeychain/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007797-Intro-DontLinkElementID_2
struct KeychainConfiguration {
static let serviceName = "MyAppService"
/*
Specifying an access group to use with `KeychainPasswordItem` instances will create items shared accross both apps.
For information on App ID prefixes, see:
https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/AppID.html
and:
https://developer.apple.com/library/ios/technotes/tn2311/_index.html
*/
// static let accessGroup = "[YOUR APP ID PREFIX].com.example.apple-samplecode.GenericKeychainShared"
/*
Not specifying an access group to use with `KeychainPasswordItem` instances
will create items specific to each app.
*/
static let accessGroup: String? = nil
}
In this file I was specifying my custom accessGroup in this line static let accessGroup = "[YOUR APP ID PREFIX].com.example.apple-samplecode.GenericKeychainShared"
After returning to static let accessGroup: String? = nil the problem was gone. :)
Make sure keychain sharing must on under Capabilities in project Target.
In my case the App_Name.entitlements file has different bundle id than of my project bundle id. So, I change bundle id in the App_Name.entitlements file as of my project bundle id.
e.g., Suppose your project bundle id is com.Apple.testApp then got to
App_Name.entitlements file open key Keychain Access Groups key which is of Array type.
Under item0 set value of your project bundle id as eg:- $(AppIdentifierPrefix)com.Apple.testAp.
According to #iCaramba's answer. I've found a workaround:
Stop the task to kill the app (if you are already running the app)
Launch the app on your device manually. DO NOT use Xcode
Use Xcode to re-launch the app

App crashes before debugger can connect

I've got an app that crashes even before the debugger can connect.
I placed a break point on the first line of main(). (I added an NSLog statement as very first statement in main() and set the break point there.
The app seems to start. The main screen with some ui elements becomes visible on the screen. Then it disappears.
There is no crash log found on the devices.
Xcode message:
Could not launch "appname"
process launch failed: failed to get the task for process xyz
Debugging is enabled of course.
The same for the profiler Instruments.
Code signing works fine so that the app can be deployed to the devices.
(Same for enterprise distribution. And the app validates for store submission.)
It does work on the simulator though.
The app used to work fine. I was just about to build it for the store. For final tests on iOS 8.1 I upgraded to Xcode 6.1 with SDK 8.1. But the problem did not occur directly after the upgrade. It worked just fine.
Then it crashed when building for release for enterprise distribution.
The AppStore build crashed in the same manner (according to Apple, the app was rejected of course.)
But it ran nicely in debug modes.
Now I was trying whether compiler options for optimization may make all the difference and I was trying to build in release mode with debugging enabled etc and end up with a debug build crashing as well. (No optimization in debug).
So it may well be that the migration to Xcode 6.1 did cause it but the problem may have come effective only after Xcode cleaned and rebuild the project in response to changes to compiler settings for code optimization.
Sorry for the long text. I tried to put everything in that may be of importance.
Reason is most likely some incompatibility of Crackify and iOS 8.1.
Therefore it may be of interest for others, altough my problem along with these symptoms may be very special.
Very early within AppDelegate didFinishLaunchingWithOptions we have had the following statement.
if ([Crackify isCracked] || [self isCertificateUnvalid])
exit(173);
That, as such, is not really well designed. The app is just terminated rather than any error message displayed to the user. Thus, it appears as if the app has crashed. But it has not crashed and therefore no crashlog is provided.
For reasons which I don't yet understand and which may not be related to this error, my debugger did not manage to hook up into the executed app. Once that was overcome (suddenly the debugger worked without any changes made to any of the debugging related settings) the error was found rather quickly.
This is Crackify: https://github.com/itruf/crackify
Within Crackify it was this code sniplet that caused the problem:
static NSString *str2 = #"ResourceRules.plist";
BOOL fileExists3 = [manager fileExistsAtPath:([NSString stringWithFormat:#"%#/%#", bundlePath, str2])];
if (!fileExists3) {
return YES;
}
For reasons that I did not further investigate, the file, that is tested here, apparently does not exist in iOS 8.1 any more.

iOS simulator crashes when using Google Maps SDK for iOS

This is driving me crazy...
I have been using Google Maps SDK for iOS for a while (even in an App Store product).
Now, I cannot make it run in the iOS simulator any longer! It doesn't matter which project I try to run (even the sample code from the SDK), it will always crash the first time a map is added, e.g.:
self.view = [GMSMapView mapWithFrame: frame camera: camera];
This is the log messages I get:
2013-05-16 10:59:01.047 SDKDemos[939:1303] ADDRESPONSE - ADDING TO MEMORY ONLY: http://dl.google.com/geosdk/latest
2013-05-16 10:59:01.050 SDKDemos[939:1b03] Google Maps SDK for iOS version: 1.2.2.3031
2013-05-16 10:59:01.050 SDKDemos[939:1b03] New version of Google Maps SDK for iOS available: 1.3.0.3430
2013-05-16 10:59:01.111 SDKDemos[939:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
I have lately tried an antivirus SW on this mac, so one theory is that it may have blocked some vital Google Maps data from downloading. Now, I have uninstalled this anti-virus SW, removed Xcode's DerivedData and reset the iOS Simulator, but with the same disappointing result.
All projects I have tried are working perfectly fine when I run them on my iPhone. I have also another mac where everything works fine on the simulator. So clearly something must have happened with this particular machine.
Any advice?
Update
Initially, I focused entirely on the first warning message (ADDRESPONSE - ADDING TO MEMORY ONLY: http://dl.google.com/geosdk/latest), but I have now realised that the only purpose of the URL mentioned there is to download a string with the latest SDK version number (currently "1.3.0.3430"). Since the SDK then correctly prints that string two lines further down, I find it very unlikely that this line is related to the real cause of the crash. (I have changed the title of this question accordingly.)
Hard to say if this really qualifies as an answer...
In any case, I'd like to document the outcome of this, in case someone else stumbles upon the same problem in the future:
After having been away a couple of days, I returned today, turned on my iMac, made a new test run, and...
The problem was gone!
Everything just worked as expected!
I have not changed a single line of code or anything at all in the Xcode configuration.
The only thing I did was to once again delete Xcode's DerivedData and reset the simulator (which I did numerous times last week, but without success at that time).
I guess that my assumption must have been right, that there must have been a cache somewhere in my machine, but outside Xcode´s DerivedData, that caused this problem. Then I was away a couple of days, and this cache simply timed out!
Even if this may sound a bit far-fetched, I cannot think of another reason for this weird behaviour.
It would have been really useful to know where this cache is located, so that one could clean it up without needing to shut down the mac for some days!

Resources