Xcode 7.3 and Swift 2.2
In a swift file I have a string extention that converts HTML text to NSAttributedString.
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil }
return html
}
}
I use it like this.
let HTMLstr = "<p><b>hello</b> world</p>"
if let attrString = HTMLstr.htmlAttributedString() {
// do something here
}
It works fine on my phone, and in the simulator, but when I archive it, it causes a crash on use of the code above. I think the problem lies in dataUsingEncoding
. Any ideas why this will crash when using an archived app.
Edit
I've included the header of the crash log:
Incident Identifier: 90C74E49-4C65-4556-B82D-6748437BB5BA
CrashReporter Key: 4fb0e685f950c6cdecf7132b26f38ff54e013348
Hardware Model: iPhone7,1
Process: AppName [7813]
Path: /private/var/containers/Bundle/Application/1EE7C00E-7600-4D72-839D-8AEA834903B8/AppName.app/AppName
Identifier: uk.co.skymook.AppName
Version: 1 (2.0)
Code Type: ARM-64 (Native)
Parent Process: launchd [1]
Date/Time: 2016-08-13 12:16:08.08 +0100
Launch Time: 2016-08-13 12:15:33.33 +0100
OS Version: iOS 9.3.2 (13F69)
Report Version: 105
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x2000000000000000
Triggered by Thread: 0
Filtered syslog:
None found
Long answer: The solution was painstakingly slow debugging. I had to go through all the code that lead up to the crash and make sure the correct checks were in place for optionals. So I had to block out lots of code, build for archive and narrow it down to a number of functions. Then I had to block out each line of code, build for archive until I found what crashes it. With hundreds of lines of code in the app, and the time it takes to archive, this was not easy. In the end, an optional got unwrapped when it was nil. Bearing in mind that it unwrapped OK in the simulator and running in debug, I was surprised to find this problem.
Short answer: It was an optional that was unwrapping with nil and not related to the code above. Memory is handled slightly differently when you archive the app, and the the complier can pass all tests for code validity.
The lesson learnt is to archive for production, and run it on the phone periodically throughout development.