Why SKProductsRequestDelegate/SKRequestDelegate didFailWithError throws EXC_BAD_ACCESS on NSError? - ios

I use SKProductsRequest to download product infos from App Store.
When I test a connectivity loss on my device, the request fails, but my app crashes within the SKRequestDelegate when I try to NSLog the error:
What am I doing wrong ? Another curious thing to me is that Expression Inspector is able to display NSError.debugDescription...
It fails on the first request, so there is no possible bug relative to multiple uses of productRequest variable (which is a strong ref in my swift class).

I finally found the reason. It is not related to SKProductsRequest!
I think there is a nasty bug with NSLogand string interpolation because when I replace:
NSLog("Failed: \(error.debugDescription)")
by
print("Failed: \(error.debugDescription)")
all is fine!
Apparently, the content of the error message can provoke a EXC_BAD_ADDRESS in NSLog (even without string interpolation in fact: NSLog(error.debugDescription) fails too).
Related anwser: https://stackoverflow.com/a/29631505/249742
NSLog("%#", error.debugDescription)
seems to work fine in every cases.
Perhaps NSLog(variable) is a misuse of NSLog, but I think NSLog(\(variable)) should be interpreted like NSLog("%#", variable). Else, there is no reliable way to interpolate strings with NSLog using the swift way \().

Related

Crash when using error.localizedDescription from completion

I'm trying to check if error.localizedDescription contains a certain string but i keep getting a crash
if error.localizedDescription.contains("\"api.error.cardRejected.2000\"") {
failCompletion()
}
I have even tried to even use another way
if let description = (error! as NSError).userInfo[NSLocalizedDescriptionKey] as? String {
if description.contains("api.error.cardRejected.2000") {
failCompletion()
}
}
I still keep getting the same crash in the logs saying
-[__NSDictionaryM domain]: unrecognized selector sent to instance 0x60000046b520
It works when i check using the debugDescription but i would like to check using the localizedDecription since the debug one only works when debugging
NSError localized description is autogenerated from what's inside, here is what API tells:
/* The primary user-presentable message for the error, for instance for NSFileReadNoPermissionError: "The file "File Name" couldn't be opened because you don't have permission to view it.". This message should ideally indicate what failed and why it failed. This value either comes from NSLocalizedDescriptionKey, or NSLocalizedFailureErrorKey+NSLocalizedFailureReasonErrorKey, or NSLocalizedFailureErrorKey. The steps this takes to construct the description include:
1. Look for NSLocalizedDescriptionKey in userInfo, use value as-is if present.
2. Look for NSLocalizedFailureErrorKey in userInfo. If present, use, combining with value for NSLocalizedFailureReasonErrorKey if available.
3. Fetch NSLocalizedDescriptionKey from userInfoValueProvider, use value as-is if present.
4. Fetch NSLocalizedFailureErrorKey from userInfoValueProvider. If present, use, combining with value for NSLocalizedFailureReasonErrorKey if available.
5. Look for NSLocalizedFailureReasonErrorKey in userInfo or from userInfoValueProvider; combine with generic "Operation failed" message.
6. Last resort localized but barely-presentable string manufactured from domain and code. The result is never nil.
*/
open var localizedDescription: String { get }
so, it is crashed (probably at step 6.) then this NSError is incorrectly constructed - so find who & how constructed it, possibly at some layer on underlying errors some key of userInfo unexpectedly is set as NSDictionary instead of NSError.

Error initialize AZSCloudStorageAccount Swift 3

I tried link to my account with this code
let storageAccount : AZSCloudStorageAccount;
try! storageAccount = AZSCloudStorageAccount(fromConnectionString: config.getAzureConnection())
let blobClient = storageAccount.getBlobClient()
var container : AZSCloudBlobContainer = (blobClient?.containerReference(fromName: config.getContainer()))!
the "config.getAzureConnection()" contains the right path because i used the same for android app.
In this line try! storageAccount = AZSCloudStorageAccount(fromConnectionString: config.getAzureConnection()) the app crash without error, only (lldb) .
Can someone help me.
Does your error look like this?
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=com.Microsoft.AzureStorage.ErrorDomain Code=1 "(null)": file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-802.0.53/src/swift/stdlib/public/core/ErrorType.swift, line 182
(lldb)
Code=1 is AZSEInvalidArgument, which means that your connection string is invalid. I am a bit confused why you said "the right path", since fromConnectionString takes the string directly, not the path to a file. To see an example of what a correct connection string looks like, please refer to the Getting Started Guide. Basically it looks like this:
"DefaultEndpointsProtocol=https;AccountName=your_account_name_here;AccountKey=your_account_key_here"
We will document the error codes properly very soon. Sorry for the confusion!
the app crash without error, only (lldb) .
I am sorry for that SWIFT blob client haven't provide error-handling code whatsoever currently. I will provide some clues to track your issue based on your code.
Before building the storage code, make one change in the project. Go to 'Azure Storage Client Library' -> Build Settings, search for the "Defines Module" setting, and change it to 'YES'.
Please check whether the issue is caused by bad network connection.
You could get error code of this issue by putting your code in a do-catch code block.
do {
//put your code here
} catch let error as NSError {
print("Error code = %ld, error domain = %#, error userinfo = %#", error.code, error.domain, error.userInfo);
}
The SWIFT blob sample has been tested and work well targeting iOS 9.0 and using XCode 7. If you have a different setup, the sample may not run properly. I suggest you use Blob Storage REST API as a workaround.

InvalidFirebaseData error when saving multiple values in Firebase

The following code once worked fine and I was able to save multiple values to a Firebase record. However this no longer works since upgrading to Swift 3 (Xcode 8). I now get the following error:
*** Terminating app due to uncaught exception 'InvalidFirebaseData', reason: '(setValue:) Cannot store object of type _SwiftValue at mood. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.'
The above error always mentions the second value, regardless of what type it is (even if it is one of the supported types like NSString). Here's what I have:
postsRef.childByAutoId().setValue(["postedBy": self.currentUser?.uid, "mood": mood, "status": status, "date": convertedDate])
This still seems to comply with the docs on the Firebase website. What am I doing wrong?
Thanks!
Try :-
let toBePosted = ["postedBy": String(self.currentUser!.uid),
"mood": String(mood), "status": String(status),
"date": String(convertedDate)]
postsRef.childByAutoId().setValue(toBePosted){ (error, ref) -> Void in
}
As for converted date you will have to convert it to NSDate format when you retrieve it.
I just had this issue and after a few hours of toying around I think I've got a solution.
It looks like Firebase is wanting you to be very specific with your data types with Swift 3.
You need to straight up tell Swift what kind of dictionary you're going to have. In this case it's probably
let toBePosted : Dictionary<String, Any> = ["postedBy": String(self.currentUser!.uid),
"mood": String(mood), "status": String(status),
"date": String(convertedDate)]
"Any" is a new thing in Swift 3 I think. AnyObject doesn't work here because Swift redefined what AnyObjects are, and Strings/Ints dont seem to be them anymore.
Finally, it seems like you have to have absolutely no optionals in your dictionary. Maybe an optional is a _SwiftValue? Once I got rid of optionals and garunteed each value was going to be there it started working for me.
This worked for me, let me know if you're still having an issue.

What is wrong with this line of Swift iOS Code?

I have created an iOS app using Swift and everything is working fine and dandy on the simulator. I get no errors or crashes at all, but when I submit my app to put up on the app store Apple rejects it and lets me know that it crashes when the user makes a selection. I cannot recreate this error/crash. I took the crash logs and symbolicated them. This line of code came up as the culprit for the crashes:
linksToPass = getLinks(season) as [String:[String]]
This line is trying to store the resulting Dictionary from the getLinks() function I created. It for sure is getting a dictionary and if there is no dictionary to send back I create a dictionary which has error information in it, so it is for sure returning a dictionary in that format no matter what. Seeing as I cannot recreate the crash, I am just trying to error check this line of code in any way possible so it does't crash when I resubmit to Apple.
I tried checking if the resulting dictionary was nil like so:
if(getLinks(seasons) != nil){
linksToPass = getLinks(season) as [String:[String]]
}
This is not valid though, and XCode lets me know that UInt8 is not compatible with NSDictionary or something of that nature.
I then fixed that line and changed it to this:
if(getLinks(seasons) != ["":[""]]){
linksToPass = getLinks(season) as [String:[String]]
}
I am just not sure if this is even a good way to check for errors. I was wondering if there were any suggestions on how I may go about making sure this line does not fail and result in a crash. Thank you very much.
EDIT:
Here is my getLinks() function if that helps add more info to the problem:
var season = ""
let hymn_links = Hymn_Links()
func getLinks (nameofseason:String) -> NSDictionary
{
switch (nameofseason)
{
default:
return ["Maps Not Found": []]
}
}
EDIT #2:
This is my updated getLinks() function with the use of optionals.
func getLinks (nameofseason:String) -> NSDictionary?
{
switch (nameofseason)
{
default:
return nil
}
}
Also in my statement of linksToPass I changed it to:
if let links = getLinks(season) as? [String:[String]]
{
linksToPass = links
hymnnames = [String] (linksToPass.keys)
}
There are some known issues with the Swift optimiser. Some people have resorted to shipping with debug builds.
My suggestion would be to test with an optimised build to see if you can reproduce it. You can then try shipping a debug build to the App store.
General Code Comments
Why are you returning an NSDictionary rather than a Swift dictionary anyway? Without knowing the contents and creation method for your hymn_links object I can't be sure how good it is.
I would avoid as casts until Swift 1.2 and stick to using as? and then handling the nil case. At least in your "Edit 2" a nil will cause a crash as nil cannot be cast to [String:[String]] although [String:[String]]? should be possible.
Can you guarantee that all of the items returned by the switch statement will never under any circumstances be nil? If not getLinks should return an Optional.
Note that is is virtually impossible for getLinks to know that one of the items will never be nil and in Swift un-handed nils are a crash waiting to happen. Unless all these methods correctly handle nil.
Return an Optional and handle that in the statement that calls getLinks.
Languages handle nils differently, Objective-C handles them rather well, Java and Swift by crashing. But Swift has a mechanism to handle nils without crashing: Optionals, use it.

iOS AddressBook Swift BadAccess

So here's the deal:
I am building an app that accesses the internal addressbook on the iPhone. Everything was working fine (and is working fine on the simulator still), but now on the device I get a ThreadBreak and lldb opens up with no error message in the console on this line:
tempPerson.firstname = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as String? ?? ""
Again, this is still working on the simulator mind you and used to work just fine.
There is some multithread action going on because I am loading the addressbook into memory in the background using GCD above:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
My addressbook was loaded properly. I have deleted the app from my test device (iPhone 6), cleaned the project (figuring it could be a bad link between some Obj-C bridge file that didn't like the ABAddressBook datatype, and even hopped on one foot while holding the phone Northward for good luck. Nothing worked.
I just can't figure out why it would work on all the Simulators and not on the phone. I do, however, notice that the app is not asking permission to access the contacts when it firsts opens after deleting (though the Authorization check is called and is granting authorization):
case .Authorized:
return self.createAddressBook()
I'm at a loss at even what to show you all since it's not returning much of anything, but here is a breakdown of the Thread Error (NOTE: Sometimes it happens on different threads...)
Thread 4
Queue: com.apple.root.background.-qos (concurrent)
0 swift_getObjectType
1 swift_dynamicCast
2 SomeApp.ViewController.(createAddressBook(SomeApp.ViewController) -> () -> Swift.Bool).(closure #1)
3_Dispatch_call_block_and_release
4_dispatch_client_callout
5_dispatch_root_queue_drain
6_dispatch_worker_thread3
7_pthread_wqthread
Enqueued from com.apple.main-thread (Thread 1)
0_dispatch_async_f_slow
*>> 1_SomeApp.ViewController.createAddressBook(SomeApp.ViewController)() -> Swift.Bool [inlined]
2_SomeApp.ViewController.determineStatus(SomeApp.ViewController)() -> Swift.Bool
3_SomeApp.ViewController.loadContacts(SomeApp.ViewController() -> ()
4_SomeApp.ViewController.viewDidLoad(SomeApp.ViewController() -> ()
... etc Viewloading stuff
On the breakpoint, the two variables given in the debugger are
The addressbookref
adbk = (AnyObject?) (instance_type = Builtin.RawPointer = 0x... EvaluatingTo: Some
and the ViewController called "Self"
self(SomeApp.ViewController)
containing all the variables my app uses elsewhere.
Sorry for being so verbose, but I really don't know what of this is relevant and what isn't..
Thanks for your help in advance!
Update: I turned off multithreading/ dispatching and it didn't work. So it must be something to do with that tempPerson.firstname bit.
Update 2: It does go around the loop twice and get two contacts before failing. I think it is hitting a nil value that isn't quite nil for some of the contacts and then crashing.. I do have the following check for it though and it is passing through:
if ABRecordCopyValue(person, kABPersonFirstNameProperty).takeRetainedValue() as AnyObject? != nil{
&
if ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue() as AnyObject? != nil{
respectively.
Update 3: Okay. So Now it seems whenever there is a blank field for first or last name it crashes (on the simulator now too). Which really sucks because I thought I put in a good check to make sure I am not accessing nil valued properties. Whats even more annoying is that I haven't changed this code and it was working fine until I removed some derived data and changed the test file to avoid a linker error. Anything that could happen in the build process that is mucking up my code?
Basically, you need to really check your type casts when accessing the addressbook, see:
tempPerson.lastname = ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue() as NSObject as? String ?? ""
The problem is that some people have really dirty addressbooks for a variety of reasons and even have some mixed up properties like having a last name property that contains "LastName, FirstName SPACE Birthday" with no firstname property.
For whatever reason, typecasting first as an NSObject BEFORE as a String seems to work well.

Resources