NSAttributedString crash when converting HTML to Attrubuted String - ios

I have a situation where try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) crashes the app.
In the console it says:
Assertion failure in void _prepareForCAFlush(UIApplication *__strong)()
The function is called in an extension String.
When I 'po' values in the console:
(lldb) po self
<p>Obfuscated string\n</p>
(lldb) po data`
450 bytes
count : 450
pointer : 0x00007fd283d75630
pointerValue : 140542131787312
(lldb) po NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
Obfuscated string
{
NSColor = "kCGColorSpaceModelRGB 0 0 0 1 ";
NSFont = "<UICTFont: 0x7fd283c47330> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 15.00pt";
NSKern = 0;
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 15, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 19/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n), Lists (\n), BaseWritingDirection 0, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0";
NSStrokeColor = "kCGColorSpaceModelRGB 0 0 0 1 ";
NSStrokeWidth = 0;
}
The string exists in a label, that is displayed in a UITableViewCell.
The function crashes in a specific case, when the "keyboard frame changes".
The Table Cells are being drawn again by iOS and this causes to redraw their content.
The crash happens on the main thread, so the function is being called on the main thread.
What could be the cause of this crash and how could I possibly resolve it?
EDIT: Table view cell code
UITableViewDataSource to generate the cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellID = cellIdentifier(for: message)
let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as! MessageTableViewCell
cell.message = message
cell.setOutletValues()
cell.selectionStyle = .none
cell.delegate = self
return cell
}
Implementaion of the Cell:
class MessageTableViewCell: UITableViewCell {
var message: Message!
// Message Body View
#IBOutlet weak var messageBodyView: ZeroPaddingTextView!
func setOutletValues() {
setMessageBodyOutletValues()
}
internal func setMessageBodyOutletValues() {
if let body = message.body {
messageBodyView.attributedText = body.htmlToPlainAttributedString()
}
}
}
And the function to create a plain attributed string, it does a few additions tothe HTML for styling (this is due to the content that comes in through the API, it needs some additions).
func htmlToPlainAttributedString() -> NSAttributedString {
let contentString = replacingOccurrences(of: "\n", with: "<br>")
let styleSheet = "body {font-family: sans-serif; font-size: 15px; color: #000000;}\n a {text-decoration: none;}\n"
let body = "<body>\(contentString)</body>"
let html = "<html><head><style type=\"text/css\">\(styleSheet)</style></head>\(body)</html>"
if let data = html.data(using: String.Encoding.unicode, allowLossyConversion: true) {
do {
return try NSAttributedString(data: data, options: [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
return NSAttributedString()
}
Console crash output:
2017-09-05 22:37:14.692 trustedfamily-ios[70389:10080542] *** Assertion failure in void _prepareForCAFlush(UIApplication *__strong)(), /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.7.47/UIApplication.m:2395
2017-09-05 22:38:14.532 trustedfamily-ios[70389:10080542] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unexpected start state'
*** First throw call stack:
(
0 CoreFoundation 0x000000010452ab0b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x00000001035e8141 objc_exception_throw + 48
2 CoreFoundation 0x000000010452ecf2 +[NSException raise:format:arguments:] + 98
3 Foundation 0x00000001031b769b -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 165
4 UIKit 0x0000000105a31575 _prepareForCAFlush + 499
5 UIKit 0x0000000105a6346b _beforeCACommitHandler + 15
6 CoreFoundation 0x00000001044d0717 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
7 CoreFoundation 0x00000001044d0687 __CFRunLoopDoObservers + 391
8 CoreFoundation 0x00000001044b5038 CFRunLoopRunSpecific + 440
9 UIFoundation 0x000000010a103edc -[NSHTMLReader _loadUsingWebKit] + 1954
10 UIFoundation 0x000000010a10522a -[NSHTMLReader attributedString] + 22
11 UIFoundation 0x000000010a09ded6 _NSReadAttributedStringFromURLOrData + 8926
12 UIFoundation 0x000000010a09bb64 -[NSAttributedString(NSAttributedStringUIFoundationAdditions) initWithData:options:documentAttributes:error:] + 117
13 trustedfamily-ios 0x0000000101e9e6ad _TTOFE5UIKitCSo18NSAttributedStringcfzT4dataV10Foundation4Data7optionsGVs10DictionarySSP__18documentAttributesGSqGVs33AutoreleasingUnsafeMutablePointerGSqCSo12NSDictionary____S0_ + 173
14 trustedfamily-ios 0x0000000101e9d9d9 _TFE5UIKitCSo18NSAttributedStringCfzT4dataV10Foundation4Data7optionsGVs10DictionarySSP__18documentAttributesGSqGVs33AutoreleasingUnsafeMutablePointerGSqCSo12NSDictionary____S0_ + 89
15 trustedfamily-ios 0x0000000101e9d803 _TFE17trustedfamily_iosSS27htmlToPlainAttributedStringfT_CSo18NSAttributedString + 1459
16 trustedfamily-ios 0x00000001020152f9 _TFC17trustedfamily_ios20MessageTableViewCell26setMessageBodyOutletValuesfT_T_ + 601
17 trustedfamily-ios 0x0000000102013467 _TFC17trustedfamily_ios20MessageTableViewCell15setOutletValuesfT_T_ + 103
18 trustedfamily-ios 0x0000000101f9a22f _TFC17trustedfamily_ios32ConversationDetailViewController9tableViewfTCSo11UITableView12cellForRowAtV10Foundation9IndexPath_CSo15UITableViewCell + 1199
19 trustedfamily-ios 0x0000000101f9a4d7 _TToFC17trustedfamily_ios32ConversationDetailViewController9tableViewfTCSo11UITableView12cellForRowAtV10Foundation9IndexPath_CSo15UITableViewCell + 87
20 UIKit 0x0000000105ba4ab2 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 750
21 UIKit 0x0000000105ba4cf8 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
22 UIKit 0x0000000105b79639 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2845
23 UIKit 0x0000000105b774a4 -[UITableView _setNeedsVisibleCellsUpdate:withFrames:] + 201
24 UIKit 0x0000000105b9626a -[UITableView _rectChangedWithNewSize:oldSize:] + 1267
25 UIKit 0x0000000105b96a5c -[UITableView setBounds:] + 322
26 UIKit 0x0000000105adee73 -[UIView(Geometry) _applyISEngineLayoutValuesToBoundsOnly:] + 598
27 UIKit 0x0000000105adf15e -[UIView(Geometry) _resizeWithOldSuperviewSize:] + 125
28 UIKit 0x000000010648f0e9 -[UIScrollView(_UIOldConstraintBasedLayoutSupport) _resizeWithOldSuperviewSize:] + 46
29 CoreFoundation 0x00000001044bb652 __53-[__NSArrayM enumerateObjectsWithOptions:usingBlock:]_block_invoke + 114
30 CoreFoundation 0x00000001044bb56f -[__NSArrayM enumerateObjectsWithOptions:usingBlock:] + 335
31 UIKit 0x0000000105addbcc -[UIView(Geometry) resizeSubviewsWithOldSize:] + 183
32 UIKit 0x00000001063fa16d -[UIView(AdditionalLayoutSupport) _is_layout] + 168
33 UIKit 0x0000000105aea0a6 -[UIView(Hierarchy) _updateConstraintsAsNecessaryAndApplyLayoutFromEngine] + 994
34 UIKit 0x0000000105afb55b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1268
35 QuartzCore 0x00000001057a4904 -[CALayer layoutSublayers] + 146
36 QuartzCore 0x0000000105798526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
37 UIKit 0x0000000105ae9334 -[UIView(Hierarchy) layoutBelowIfNeeded] + 1108
38 trustedfamily-ios 0x0000000101fe3f4c _TFC17trustedfamily_ios32ConversationDetailViewController28changeBottomLayoutConstraintfT2toV12CoreGraphics7CGFloat_T_ + 284
39 trustedfamily-ios 0x0000000101fe3fac _TToFC17trustedfamily_ios32ConversationDetailViewController28changeBottomLayoutConstraintfT2toV12CoreGraphics7CGFloat_T_ + 44
40 trustedfamily-ios 0x0000000101fe3bf7 _TFFC17trustedfamily_ios32ConversationDetailViewController28changeBottomLayoutConstraintFT2toV12CoreGraphics7CGFloat8animatedSb8durationSd7optionsVSC22UIViewAnimationOptions_T_U_FT_T_ + 39
41 trustedfamily-ios 0x0000000101e572d7 _TTRXFo___XFdCb___ + 39
42 UIKit 0x0000000105af13da +[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:animationStateGenerator:completion:] + 572
43 UIKit 0x0000000105af18dd +[UIView(UIViewAnimationWithBlocks) animateWithDuration:delay:options:animations:completion:] + 99
44 trustedfamily-ios 0x0000000101fe3b7f _TFC17trustedfamily_ios32ConversationDetailViewController28changeBottomLayoutConstraintfT2toV12CoreGraphics7CGFloat8animatedSb8durationSd7optionsVSC22UIViewAnimationOptions_T_ + 943
45 trustedfamily-ios 0x0000000101fe3e1f _TToFC17trustedfamily_ios32ConversationDetailViewController28changeBottomLayoutConstraintfT2toV12CoreGraphics7CGFloat8animatedSb8durationSd7optionsVSC22UIViewAnimationOptions_T_ + 79
46 trustedfamily-ios 0x0000000101fe30e6 _TFC17trustedfamily_ios32ConversationDetailViewController23keyboardWillChangeFramefV10Foundation12NotificationT_ + 2278
47 trustedfamily-ios 0x0000000101fe3237 _TToFC17trustedfamily_ios32ConversationDetailViewController23keyboardWillChangeFramefV10Foundation12NotificationT_ + 71
48 CoreFoundation 0x00000001044c9c2c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
49 CoreFoundation 0x00000001044c9b29 _CFXRegistrationPost + 425
50 CoreFoundation 0x00000001044c9892 ___CFXNotificationPost_block_invoke + 50
51 CoreFoundation 0x000000010448d102 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1826
52 CoreFoundation 0x000000010448c261 _CFXNotificationPost + 673
53 Foundation 0x00000001030b6ca4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 66
54 UIKit 0x000000010649ce05 -[UIInputWindowController postStartNotifications:withInfo:] + 225
55 UIKit 0x000000010649f0af __77-[UIInputWindowController moveFromPlacement:toPlacement:starting:completion:]_block_invoke.871 + 381
56 UIKit 0x0000000105af13da +[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:animationStateGenerator:completion:] + 572
57 UIKit 0x0000000105af1853 +[UIView(UIViewAnimationWithBlocks) _animateWithDuration:delay:options:animations:start:completion:] + 116
58 UIKit 0x000000010649eacb -[UIInputWindowController moveFromPlacement:toPlacement:starting:completion:] + 1503
59 UIKit 0x00000001064a6d5e __43-[UIInputWindowController setInputViewSet:]_block_invoke.1318 + 97
60 UIKit 0x000000010649a59a -[UIInputWindowController performOperations:withTemplateNotificationInfo:] + 46
61 UIKit 0x00000001064a68ea -[UIInputWindowController setInputViewSet:] + 1753
62 UIKit 0x000000010649e14c -[UIInputWindowController performOperations:withAnimationStyle:] + 50
63 UIKit 0x0000000106114a8a -[UIPeripheralHost(UIKitInternal) setInputViews:animationStyle:] + 1505
64 UIKit 0x0000000106115c4b -[UIPeripheralHost(UIKitInternal) _preserveInputViewsWithId:animated:reset:] + 499
65 UIKit 0x0000000105bec35d -[UIViewController _presentViewController:modalSourceViewController:presentationController:animationController:interactionController:completion:] + 1145
66 UIKit 0x0000000105bedfae -[UIViewController _presentViewController:withAnimationController:completion:] + 4660
67 CoreFoundation 0x00000001044b2c6c __invoking___ + 140
68 CoreFoundation 0x00000001044b2b40 -[NSInvocation invoke] + 320
69 UIKit 0x0000000105bd1633 -[_UIDelayedPresentationContext finishDelayedPresentation:] + 230
70 UIKit 0x0000000105be9416 -[UIViewController _endDelayingPresentation] + 93
71 CoreFoundation 0x00000001044b2c6c __invoking___ + 140
72 CoreFoundation 0x00000001044b2b40 -[NSInvocation invoke] + 320
73 FrontBoardServices 0x000000010a1f25f6 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
74 FrontBoardServices 0x000000010a1f246d -[FBSSerialQueue _performNext] + 186
75 FrontBoardServices 0x000000010a1cb360 -[FBSWorkspace synchronizeSystemAnimationFencesWithCleanUpBlock:] + 1549
76 UIKit 0x0000000105a311d4 -[UIApplication _synchronizeSystemAnimationFencesWithSpinCleanUpBlock:] + 543
77 UIKit 0x0000000105ab22cd __realPreCommitHandler_block_invoke + 395
78 QuartzCore 0x000000010575532c _ZNK2CA11Transaction5Fence13run_callbacksEv + 40
79 QuartzCore 0x0000000105727f7c _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 528
80 QuartzCore 0x0000000105754130 _ZN2CA11Transaction6commitEv + 468
81 QuartzCore 0x0000000105754b37 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 115
82 CoreFoundation 0x00000001044d0717 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
83 CoreFoundation 0x00000001044d0687 __CFRunLoopDoObservers + 391
84 CoreFoundation 0x00000001044b5720 __CFRunLoopRun + 1200
85 CoreFoundation 0x00000001044b5016 CFRunLoopRunSpecific + 406
86 GraphicsServices 0x000000010a9eda24 GSEventRunModal + 62
87 UIKit 0x0000000105a38134 UIApplicationMain + 159
88 trustedfamily-ios 0x0000000101ff6837 main + 55
89 libdyld.dylib 0x000000010894465d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Try to make your html convert in NSAttributedString inside
DispatchQueue.main.async {
}

I'm seeing this crash in a very similar situation in the field but can't reproduce it myself.
Let's try this and see if it helps:
guard UIApplication.shared.applicationState == .active else { return NSAttributedString() }

Related

NSInvalidArgumentException - Attempt to insert nil object from objects

I had the error below:
'*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[1]'
it happens when I try to save texts from textfields using saveInBackground or other kind of saving method of Parse. Because code is little, all code is pasted below:
#IBAction func onSave(_ sender: Any) {
let profile = PFObject(className: "Info")
profile["preferredName"] = nameTextField.text!
profile["major"] = majorTextField.text!
profile["introduction"] = bioTextView.text!
let segmentIndex = yearSegmented.selectedSegmentIndex
UserDefaults.standard.set(segmentIndex, forKey: "segmentIndex")
profile["year"] = yearSegmented.titleForSegment(at: segmentIndex)!
print(profile.allKeys) // print keys in profile
print(profile.value(forKey: "introduction")!, profile.value(forKey: "major")!,
profile.value(forKey: "year")!, profile.value(forKey: "preferredName")!) // print values in profile
profile.saveInBackground(block: { (success, error) in // line where the error happens
if success {
UserDefaults.standard.set(true, forKey: "hasProfile")
print("profile saved")
} else {
print("failed to save profile")
}
})
This is how Parse IOS Guide told me about how to save objects:
let gameScore = PFObject(className:"GameScore")
gameScore["score"] = 1337
gameScore["playerName"] = "Sean Plott"
gameScore["cheatMode"] = false
gameScore.saveInBackground { (succeeded, error) in
if (succeeded) {
// The object has been saved.
} else {
// There was a problem, check error.description
}
}
I tested if any content in profile is nil, but all keys and values are there and can be printed. I don't see anything nil here, so I cannot understand this error. If anyone could shed some light to enlighten me, I would be be very grateful for this.
In case anyone needs the stack trace:
0 CoreFoundation 0x00000001803f25e4 __exceptionPreprocess + 236
1 libobjc.A.dylib 0x000000018019813c objc_exception_throw + 56
2 CoreFoundation 0x00000001804775b4 -[__NSCFString characterAtIndex:].cold.1 + 0
3 CoreFoundation 0x0000000180474fc4 -[__NSPlaceholderArray initWithCapacity:].cold.1 + 0
4 CoreFoundation 0x00000001802ef138 -[__NSPlaceholderArray initWithObjects:count:] + 184
5 CoreFoundation 0x00000001803dddec +[NSArray arrayWithObjects:count:] + 44
6 Parse 0x0000000104eda478 -[PFTaskQueue enqueue:] + 380
7 Parse 0x0000000104e78b2c -[PFObject saveInBackground] + 148
8 Parse 0x0000000104e78c1c -[PFObject saveInBackgroundWithBlock:] + 68
9 StudyMate 0x00000001041c59bc $s9StudyMate18EditViewControllerC6onSaveyyypF + 7276
10 StudyMate 0x00000001041c5fe4 $s9StudyMate18EditViewControllerC6onSaveyyypFTo + 68
11 UIKitCore 0x0000000184d81fa0 -[UIApplication sendAction:to:from:forEvent:] + 96
12 UIKitCore 0x00000001842a7714 -[UIBarButtonItem _triggerActionForEvent:] + 176
13 UIKitCore 0x000000018427fe24 __45-[_UIButtonBarTargetAction _invoke:forEvent:]_block_invoke + 36
14 UIKitCore 0x000000018427fcd8 -[_UIButtonBarTargetAction _invoke:forEvent:] + 168
15 UIKitCore 0x0000000184d81fa0 -[UIApplication sendAction:to:from:forEvent:] + 96
16 UIKitCore 0x0000000184680bd8 -[UIControl sendAction:to:forEvent:] + 124
17 UIKitCore 0x0000000184680fc0 -[UIControl _sendActionsForEvents:withEvent:] + 352
18 UIKitCore 0x0000000184681010 -[UIControl _sendActionsForEvents:withEvent:] + 432
19 UIKitCore 0x000000018467f8e8 -[UIControl touchesEnded:withEvent:] + 516
20 UIKitCore 0x0000000184dc0af0 -[UIWindow _sendTouchesForEvent:] + 1104
21 UIKitCore 0x0000000184dc25d4 -[UIWindow sendEvent:] + 4332
22 UIKitCore 0x0000000184d9a390 -[UIApplication sendEvent:] + 784
23 UIKitCore 0x0000000184e286f4 __dispatchPreprocessedEventFromEventQueue + 7520
24 UIKitCore 0x0000000184e2a770 __processEventQueue + 6764
25 UIKitCore 0x0000000184e22760 __eventFetcherSourceCallback + 184
26 CoreFoundation 0x0000000180360820 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
27 CoreFoundation 0x0000000180360720 __CFRunLoopDoSource0 + 204
28 CoreFoundation 0x000000018035fab0 __CFRunLoopDoSources0 + 256
29 CoreFoundation 0x000000018035a004 __CFRunLoopRun + 744
30 CoreFoundation 0x0000000180359804 CFRunLoopRunSpecific + 572
31 GraphicsServices 0x000000018c23660c GSEventRunModal + 160
32 UIKitCore 0x0000000184d7bd2c -[UIApplication _run] + 992
33 UIKitCore 0x0000000184d808c8 UIApplicationMain + 112
34 libswiftUIKit.dylib 0x00000001b6766224 $s5UIKit17UIApplicationMainys5Int32VAD_SpySpys4Int8VGGSgSSSgAJtF + 100
35 StudyMate 0x00000001041c7a9c $sSo21UIApplicationDelegateP5UIKitE4mainyyFZ + 104
36 StudyMate 0x00000001041c7a24 $s9StudyMate11AppDelegateC5$mainyyFZ + 44
37 StudyMate 0x00000001041c7b20 main + 28
38 dyld 0x0000000104501cd8 start_sim + 20
39 ??? 0x0000000104451088 0x0 + 4366602376
40 ??? 0xb23a000000000000 0x0 + 12842577287400390656

Invalid update of a UIDatePicker inside tableView crashing in iOS 13 on rotation

I am adding a UIDatePicker as a table's footer. I have another extension of UITableView which implements traitCollectionDidChange and only does beginUpdates and endUpdates. I am getting the below crash on changing the orientation.
*** Assertion failure in -[UIPickerTableView _Bug_Detected_In_Client_Of_UITableView_Invalid_Number_Of_Rows_In_Section:],
/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore_Sim/UIKit-3901.4.2/UITableView.m:2407
2020-05-12 13:35:28.729340+0530 MyApplication[41892:1575639] *** Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.
The number of rows contained in an existing section after the update (0) must be equal to the number of
rows contained in that section before the update (10000), plus or minus the number of rows inserted or
deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into
or out of that section (0 moved in, 0 moved out).'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff23c7127e __exceptionPreprocess + 350
1 libobjc.A.dylib 0x00007fff513fbb20 objc_exception_throw + 48
2 CoreFoundation 0x00007fff23c70ff8 +[NSException raise:format:arguments:] + 88
3 Foundation 0x00007fff256e9b51 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 191
4 UIKitCore 0x00007fff4825d508 -[UITableView _Bug_Detected_In_Client_Of_UITableView_Invalid_Number_Of_Rows_In_Section:] + 193
5 UIKitCore 0x00007fff4825cdc1 -[UITableView _endCellAnimationsWithContext:] + 16657
6 UIKitCore 0x00007fff48276e0b -[UITableView endUpdatesWithContext:] + 112
7 MyApplication 0x0000000103d13ed1 -[UITableView(RIAdditions) traitCollectionDidChange:] + 97
8 UIKitCore 0x00007fff4854ccc4 -[UIView _traitCollectionDidChangeInternal:] + 977
9 UIKitCore 0x00007fff4854d5c4 -[UIView _wrappedProcessTraitCollectionDidChange:forceNotification:] + 161
10 UIKitCore 0x00007fff4854d80a -[UIView _wrappedProcessTraitCollectionDidChange:forceNotification:] + 743
11 UIKitCore 0x00007fff4854d80a -[UIView _wrappedProcessTraitCollectionDidChange:forceNotification:] + 743
12 UIKitCore 0x00007fff4854d80a -[UIView _wrappedProcessTraitCollectionDidChange:forceNotification:] + 743
13 UIKitCore 0x00007fff4854d80a -[UIView _wrappedProcessTraitCollectionDidChange:forceNotification:] + 743
14 UIKitCore 0x00007fff4854d80a -[UIView _wrappedProcessTraitCollectionDidChange:forceNotification:] + 743
15 UIKitCore 0x00007fff4854d7ae -[UIView _wrappedProcessTraitCollectionDidChange:forceNotification:] + 651
16 UIKitCore 0x00007fff4854d935 -[UIView _processDidChangeRecursivelyFromOldTraits:toCurrentTraits:forceNotification:] + 140
17 UIKitCore 0x00007fff485783d2 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2243
18 QuartzCore 0x00007fff2b131db1 -[CALayer layoutSublayers] + 255
19 QuartzCore 0x00007fff2b137fa3 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 517
20 UIKitCore 0x00007fff48563635 -[UIView(Hierarchy) layoutBelowIfNeeded] + 980
21 UIKitCore 0x00007fff47978038 -[UINavigationController _layoutViewController:] + 1465
22 UIKitCore 0x00007fff479710e9 -[UINavigationController _layoutTopViewControllerLookForNested:] + 589
23 UIKitCore 0x00007fff47966e9a __105-[UINavigationController _repositionPaletteWithNavigationBarHidden:duration:shouldUpdateNavigationItems:]_block_invoke + 718
24 UIKitCore 0x00007fff47966b9c -[UINavigationController _repositionPaletteWithNavigationBarHidden:duration:shouldUpdateNavigationItems:] + 308
25 UIKitCore 0x00007fff47970339 -[UINavigationController _updateBarsForCurrentInterfaceOrientationAndForceBarLayout:] + 174
26 UIKitCore 0x00007fff47980763 __84-[UINavigationController willTransitionToTraitCollection:withTransitionCoordinator:]_block_invoke + 639
27 UIKitCore 0x00007fff47a42124 -[_UIViewControllerTransitionCoordinator _applyBlocks:releaseBlocks:] + 294
28 UIKitCore 0x00007fff47a3e446 -[_UIViewControllerTransitionContext __runAlongsideAnimations] + 263
29 UIKitCore 0x00007fff4856bde6 +[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:animationStateGenerator:completion:] + 528
30 UIKitCore 0x00007fff4856c395 +[UIView(UIViewAnimationWithBlocks) animateWithDuration:delay:options:animations:completion:] + 99
31 UIKitCore 0x00007fff47a5665a __58-[_UIWindowRotationAnimationController animateTransition:]_block_invoke_2 + 278
32 UIKitCore 0x00007fff4856ff44 +[UIView(Internal) _performBlockDelayingTriggeringResponderEvents:forScene:] + 174
33 UIKitCore 0x00007fff47a563e8 __58-[_UIWindowRotationAnimationController animateTransition:]_block_invoke + 164
34 UIKitCore 0x00007fff4856bde6 +[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:animationStateGenerator:completion:] + 528
35 UIKitCore 0x00007fff4856c395 +[UIView(UIViewAnimationWithBlocks) animateWithDuration:delay:options:animations:completion:] + 99
36 UIKitCore 0x00007fff47a562c0 -[_UIWindowRotationAnimationController animateTransition:] + 491
37 UIKitCore 0x00007fff480d2e9d -[UIWindow _rotateToBounds:withAnimator:transitionContext:] + 525
38 UIKitCore 0x00007fff480d58e0 -[UIWindow _rotateWindowToOrientation:updateStatusBar:duration:skipCallbacks:] + 2331
39 UIKitCore 0x00007fff480d5ed3 -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:isRotating:] + 633
40 UIKitCore 0x00007fff480d4e27 -[UIWindow _setRotatableViewOrientation:updateStatusBar:duration:force:] + 119
41 UIKitCore 0x00007fff480d3ca4 __57-[UIWindow _updateToInterfaceOrientation:duration:force:]_block_invoke + 111
42 UIKitCore 0x00007fff480d3bcd -[UIWindow _updateToInterfaceOrientation:duration:force:] + 455
43 CoreFoundation 0x00007fff23b9b5bc __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
44 CoreFoundation 0x00007fff23b9aa35 _CFXRegistrationPost1 + 421
45 CoreFoundation 0x00007fff23b9a7a1 ___CFXNotificationPost_block_invoke + 193
46 CoreFoundation 0x00007fff23c988b3 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1811
47 CoreFoundation 0x00007fff23b9a0f6 _CFXNotificationPost + 950
48 Foundation 0x00007fff2574bbf7 -[NSNotificationCenter postNotificationName:object:userInfo:] + 59
49 UIKitCore 0x00007fff47cd5955 -[UIDevice setOrientation:animated:] + 224
50 UIKitCore 0x00007fff477c83f1 __134-[_UIWindowSceneDeviceOrientationSettingsDiffAction _updateDeviceOrientationWithSettingObserverContext:windowScene:transitionContext:]_block_invoke + 137
51 UIKitCore 0x00007fff47bd8c83 +[BSAnimationSettings(UIKit) tryAnimatingWithSettings:actions:completion:] + 865
52 UIKitCore 0x00007fff47cd2dff _UISceneSettingsDiffActionPerformChangesWithTransitionContext + 240
53 UIKitCore 0x00007fff477c8336 -[_UIWindowSceneDeviceOrientationSettingsDiffAction _updateDeviceOrientationWithSettingObserverContext:windowScene:transitionContext:] + 248
54 UIKitCore 0x00007fff477c8231 __163-[_UIWindowSceneDeviceOrientationSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:]_block_invoke + 112
55 UIKitCore 0x00007fff47cd2d02 _UISceneSettingsDiffActionPerformActionsWithDelayForTransitionContext + 84
56 UIKitCore 0x00007fff477c80c1 -[_UIWindowSceneDeviceOrientationSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:] + 216
57 UIKitCore 0x00007fff476206e7 __64-[UIScene scene:didUpdateWithDiff:transitionContext:completion:]_block_invoke + 657
58 UIKitCore 0x00007fff4761f26c -[UIScene _emitSceneSettingsUpdateResponseForCompletion:afterSceneUpdateWork:] + 248
59 UIKitCore 0x00007fff47620411 -[UIScene scene:didUpdateWithDiff:transitionContext:completion:] + 210
60 UIKitCore 0x00007fff47bfac66 -[UIApplicationSceneClientAgent scene:handleEvent:withCompletion:] + 504
61 FrontBoardServices 0x00007fff365d6c07 -[FBSSceneImpl updater:didUpdateSettings:withDiff:transitionContext:completion:] + 565
62 FrontBoardServices 0x00007fff365fc99f __88-[FBSWorkspaceScenesClient sceneID:updateWithSettingsDiff:transitionContext:completion:]_block_invoke_2 + 123
63 FrontBoardServices 0x00007fff365e0c45 -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 220
64 FrontBoardServices 0x00007fff365fc8dc __88-[FBSWorkspaceScenesClient sceneID:updateWithSettingsDiff:transitionContext:completion:]_block_invoke + 196
65 libdispatch.dylib 0x000000010610ed48 _dispatch_client_callout + 8
66 libdispatch.dylib 0x0000000106111cb9 _dispatch_block_invoke_direct + 300
67 FrontBoardServices 0x00007fff3662237e __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 30
68 FrontBoardServices 0x00007fff3662206c -[FBSSerialQueue _queue_performNextIfPossible] + 441
69 FrontBoardServices 0x00007fff3662257b -[FBSSerialQueue _performNextFromRunLoopSource] + 22
70 CoreFoundation 0x00007fff23bd4471 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
71 CoreFoundation 0x00007fff23bd439c __CFRunLoopDoSource0 + 76
72 CoreFoundation 0x00007fff23bd3b74 __CFRunLoopDoSources0 + 180
73 CoreFoundation 0x00007fff23bce87f __CFRunLoopRun + 1263
74 CoreFoundation 0x00007fff23bce066 CFRunLoopRunSpecific + 438
75 GraphicsServices 0x00007fff384c0bb0 GSEventRunModal + 65
76 UIKitCore 0x00007fff48092d4d UIApplicationMain + 1621
77 MyApplication 0x00000001041a68db main + 107
78 libdyld.dylib 0x00007fff5227ec25 start + 1
79 ??? 0x0000000000000002 0x0 + 2
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I found out that this crash happens specifically due to datePicker(or may be the table inside it) i.e. UIPickerTableView. Code crashes at line self.endUpdates() for UIPickerTableView. Please find the code of the dummy app I created:
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let datePicker = UIDatePicker()
datePicker.datePickerMode = .date
self.tableView.tableFooterView = datePicker
}
}
extension UITableView {
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.beginUpdates()
self.endUpdates()
}
}
Would be glad if anyone could help me understand the root cause of this crash.
After comments and some testing...
the crash occurs on iOS 13.3, but not on iOS 13.4
on iOS 13.4, traitCollectionDidChange in the extension is not even called
on iOS 13.3, it is called, and in fact is called 10 times (my quick testing observation)
repeatedly calling beginUpdates() endUpdates() is causing the crash
those calls are probably (almost certainly) not needed to begin with
A little clarification on beginUpdates() endUpdates() ...
They tell the table view to process / animate changes to the table without reloading the cells. A common usage is for expanding / collapsing cells, using a "callback" closure.
Assume a custom cell with various UI elements, including an "Expand / Collapse" button. The code in cellForRowAt may look like this:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "sCell", for: indexPath) as! SimpleCell
c.myLabel.text = "\(indexPath)"
c.callback = {
c.myHeightConstraint.constant = c.myHeightConstraint.constant == 21 ? 60 : 21
tableView.beginUpdates()
tableView.endUpdates()
}
return c
}
When the button is tapped in the cell, it calls back to the closure which toggles our cell's myHeightConstraint between 21 and 60. With those calls, we see the row's height animate. Without those calls, the row doesn't change height until something else tells the table view to re-caclulate / re-layout the rows.
Note that Apple's docs state those calls are being phased-out / deprecated in favor of performBatchUpdates():
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "sCell", for: indexPath) as! SimpleCell
c.myLabel.text = "\(indexPath)"
c.callback = {
c.myHeightConstraint.constant = c.myHeightConstraint.constant == 21 ? 60 : 21
tableView.performBatchUpdates(nil, completion: nil)
}
return c
}
will accomplish the same thing.
So, as those calls are not doing anything - other than causing the crash - it sounds like they should be removed.

Adding subview self causing crash in swift 4.1

I have a custom view whose init method is as below. This used to work fine in Xcode 9.1 with swift 4. Today I updated to Xcode 9.3 and set the project base to swift 4.1 and it started crashing in this init method.
init(frame: CGRect, detailDic: [[String:AnyObject]], parentView:UIView)
{
super.init(frame:frame)
self.view = Utilities.loadViewFromNib(“MyScoreView", atIndex: 0, aClass: type(of: self),parent:self) as! UIView
self.view.frame = frame
self.view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
self.view.isHidden = true
finalScoreTable.register(UINib(nibName: “MyScoreTableViewCell", bundle: nil), forCellReuseIdentifier: "scoreCell")
addSubview(self.view)
parentView.addSubview(self) //Crashes here
finalScoreTable.tableFooterView = UIView()
}
Crash stack trace
*** First throw call stack:
(
0 CoreFoundation 0x0000000104a471e6 __exceptionPreprocess + 294
1 libobjc.A.dylib 0x0000000103651031 objc_exception_throw + 48
2 CoreFoundation 0x0000000104ac8784 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 UIKit 0x00000001066ea73b -[UIResponder doesNotRecognizeSelector:] + 295
4 CoreFoundation 0x00000001049c9898 ___forwarding___ + 1432
5 CoreFoundation 0x00000001049c9278 _CF_forwarding_prep_0 + 120
6 UIKit 0x0000000106626851 -[UITableView _numberOfRowsInSection:] + 62
7 UIKit 0x00000001068d5e5b -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] + 2631
8 UIKit 0x00000001068dc219 -[UITableViewRowData rectForFooterInSection:heightCanBeGuessed:] + 487
9 UIKit 0x00000001068dc37f -[UITableViewRowData heightForTable] + 61
10 UIKit 0x00000001065d684e -[UITableView _updateContentSize] + 365
11 UIKit 0x0000000106605a8f -[UITableView _rebuildGeometry] + 66
12 UIKit 0x0000000106603583 -[UITableView didMoveToWindow] + 145
13 UIKit 0x0000000106581f55 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 1718
14 UIKit 0x000000010659b73e -[UIScrollView _didMoveFromWindow:toWindow:] + 84
15 UIKit 0x0000000106581b98 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 761
16 UIKit 0x0000000106581b98 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 761
17 UIKit 0x0000000106574114 __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 151
18 UIKit 0x0000000106573fea -[UIView(Hierarchy) _postMovedFromSuperview:] + 808
19 UIKit 0x0000000106584a2b -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1940
20 MySampleApp 0x0000000102649ec7 _T017MySampleApp14MyScoreViewCACSC6CGRectV5frame_Says10DictionaryVySSyXlGG13playerDetailsSo6UIViewC06parentF0tcfc + 4343
21 MySampleApp 0x0000000102648dc7 _T017MySampleApp14MyScoreViewCACSC6CGRectV5frame_Says10DictionaryVySSyXlGG13playerDetailsSo6UIViewC06parentF0tcfC + 87
22 MySampleApp 0x00000001026371b8 _T017MySampleApp22MainGameViewControllerC14showScoreAlertySo5TimerCF + 2200
23 MySampleApp 0x000000010263784c _T017MySampleApp22MainGameViewControllerC14showScoreAlertySo5TimerCFTo + 60
24 Foundation 0x00000001030bb4dd __NSFireTimer + 83
25 CoreFoundation 0x00000001049d6e64 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
26 CoreFoundation 0x00000001049d6a52 __CFRunLoopDoTimer + 1026
27 CoreFoundation 0x00000001049d660a __CFRunLoopDoTimers + 266
28 CoreFoundation 0x00000001049cde4c __CFRunLoopRun + 2252
29 CoreFoundation 0x00000001049cd30b CFRunLoopRunSpecific + 635
30 GraphicsServices 0x000000010c816a73 GSEventRunModal + 62
31 UIKit 0x00000001064bc0b7 UIApplicationMain + 159
32 MySampleApp 0x00000001026580e7 main + 55
33 libdyld.dylib 0x00000001093d4955 start + 1
34 ??? 0x0000000000000001 0x0 + 1
)

swift NSWritingDirection causing crash in NSAttributedString

I have a code like this:
let myString = "Swift Attributed String"
let myAttribute = [ NSAttributedStringKey.foregroundColor: UIColor.blue , NSAttributedStringKey.writingDirection:(NSWritingDirection.rightToLeft.rawValue|NSWritingDirectionFormatType.override.rawValue)] as [NSAttributedStringKey : Any]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
// set attributed text on a UILabel
self.labelUsername.attributedText = myAttrString
The app is crashing on above line. If I remove NSAttributedStringKey.writingDirection from the attribute dictionary, the crash goes away.
Here's the crash log:
2018-03-20 14:38:59.077 Haraj Swift[90519:25834245] -[__NSCFNumber countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xb000000000000033
2018-03-20 14:38:59.092 Haraj Swift[90519:25834245] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xb000000000000033'
*** First throw call stack:
(
0 CoreFoundation 0x000000010ef6434b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000010e9c521e objc_exception_throw + 48
2 CoreFoundation 0x000000010efd3f34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x000000010eee9c15 ___forwarding___ + 1013
4 CoreFoundation 0x000000010eee9798 _CF_forwarding_prep_0 + 120
5 UIFoundation 0x00000001176e13b3 -[NSATSGlyphStorage setGlyphRange:characterRange:] + 2709
6 UIFoundation 0x00000001176dc5ec -[NSATSTypesetter _ctTypesetter] + 287
7 UIFoundation 0x00000001176e6ef7 -[NSATSLineFragment layoutForStartingGlyphAtIndex:characterIndex:minPosition:maxPosition:lineFragmentRect:] + 95
8 UIFoundation 0x00000001176dd540 -[NSATSTypesetter _layoutLineFragmentStartingWithGlyphAtIndex:characterIndex:atPoint:renderingContext:] + 3240
9 UIFoundation 0x00000001176eeb84 -[NSSingleLineTypesetter createRenderingContextForCharacterRange:typesetterBehavior:usesScreenFonts:hasStrongRight:syncDirection:mirrorsTextAlignment:maximumWidth:] + 408
10 UIFoundation 0x0000000117724167 __NSStringDrawingEngine + 27441
11 UIFoundation 0x00000001177263d4 -[NSAttributedString(NSExtendedStringDrawing) boundingRectWithSize:options:context:] + 797
12 UIKit 0x000000010fd1f744 -[UILabel _textRectForBounds:limitedToNumberOfLines:includingShadow:] + 1199
13 UIKit 0x000000010fd1f05b -[UILabel textRectForBounds:limitedToNumberOfLines:] + 68
14 UIKit 0x000000010fd24b7f -[UILabel _intrinsicSizeWithinSize:] + 168
15 UIKit 0x000000010fd24c6c -[UILabel intrinsicContentSize] + 92
16 UIKit 0x00000001104679ed -[UIView(UIConstraintBasedLayout) _generateContentSizeConstraints] + 35
17 UIKit 0x00000001104676ea -[UIView(UIConstraintBasedLayout) _updateContentSizeConstraints] + 494
18 UIKit 0x00000001104714d6 -[UIView(AdditionalLayoutSupport) _updateSystemConstraints] + 66
19 UIKit 0x000000011046ff3e -[UIView(AdditionalLayoutSupport) _sendUpdateConstraintsIfNecessaryForSecondPass:] + 161
20 UIKit 0x000000011047039d -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededCollectingViews:forSecondPass:] + 860
21 UIKit 0x00000001104702fa -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededCollectingViews:forSecondPass:] + 697
22 UIKit 0x00000001104702fa -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededCollectingViews:forSecondPass:] + 697
23 Foundation 0x000000010e4e1bd0 -[NSISEngine withBehaviors:performModifications:] + 155
24 UIKit 0x00000001104705f2 -[UIView(AdditionalLayoutSupport) _recursiveUpdateConstraintsIfNeededCollectingViews:forSecondPass:] + 118
25 UIKit 0x00000001104702fa -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededCollectingViews:forSecondPass:] + 697
26 UIKit 0x00000001104702fa -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededCollectingViews:forSecondPass:] + 697
27 Foundation 0x000000010e4e1bd0 -[NSISEngine withBehaviors:performModifications:] + 155
28 UIKit 0x0000000110470c71 __97-[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededPostponeVariableChangeNotifications:]_block_invoke + 91
29 UIKit 0x000000011046fa9b -[UIView(AdditionalLayoutSupport) _withUnsatisfiableConstraintsLoggingSuspendedIfEngineDelegateExists:] + 117
30 UIKit 0x0000000110470757 -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededPostponeVariableChangeNotifications:] + 181
31 UIKit 0x000000011047184d -[UIView(AdditionalLayoutSupport) _updateConstraintsAtEngineLevelIfNeededPostponeVariableChangeNotifications:] + 356
32 UIKit 0x000000010fb4b922 -[UIView(Hierarchy) _updateConstraintsAsNecessaryAndApplyLayoutFromEngine] + 159
33 UIKit 0x000000010fb5cf50 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237
34 QuartzCore 0x0000000117054cc4 -[CALayer layoutSublayers] + 146
35 QuartzCore 0x0000000117048788 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
36 QuartzCore 0x0000000117048606 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
37 QuartzCore 0x0000000116fd6680 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280
38 QuartzCore 0x0000000117003767 _ZN2CA11Transaction6commitEv + 475
39 QuartzCore 0x00000001170040d7 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 113
40 CoreFoundation 0x000000010ef08e17 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
41 CoreFoundation 0x000000010ef08d87 __CFRunLoopDoObservers + 391
42 CoreFoundation 0x000000010eeedb9e __CFRunLoopRun + 1198
43 CoreFoundation 0x000000010eeed494 CFRunLoopRunSpecific + 420
44 GraphicsServices 0x0000000116f37a6f GSEventRunModal + 161
45 UIKit 0x000000010fa98964 UIApplicationMain + 159
46 Haraj Swift 0x000000010de9e8a7 main + 55
47 libdyld.dylib 0x0000000112fe168d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Try using an array of NSWritingDirection
let myString = "Swift Attributed String"
let myAttrString = NSAttributedString(string: myString, attributes: [.foregroundColor : UIColor.blue, .writingDirection: [NSWritingDirection.rightToLeft.rawValue]])
self.label.attributedText = myAttrString
Let me know if you still face any issues.
According to documentation, you have to use a NSNumber for indicate the value
Array NSNumber Values
Writing Direction Constants
0 -> NSWritingDirectionLeftToRight | NSTextWritingDirectionEmbedding
1 -> NSWritingDirectionRightToLeft | NSTextWritingDirectionEmbedding
2 -> NSWritingDirectionLeftToRight | NSTextWritingDirectionOverride
3 -> NSWritingDirectionRightToLeft | NSTextWritingDirectionOverride
So, you can do that by this way
let myString = "Swift Attributed String"
let attr:[NSAttributedStringKey: Any] = [.foregroundColor: UIColor.blue, .writingDirection: [NSNumber(integerLiteral: 3)]]
let myAttrString = NSAttributedString(string: myString, attributes:attr)
self.label.attributedText = myAttrString

strange crash in iOS

There is a group of crashes reported by crittercism.
I've never reproduced it but there're about 50 times from different users in 1 weeks.
21
XXApp 0x0000000100129fb0 -[NSString(XXFormat) attributedStringFromHTMLByFont:] (NSString+XXFormat.m:15) was crashed.
Following is The line 15 code in NSString+XXFormat.m:
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithData:[self dataUsingEncoding:NSUTF8StringEncoding]
options:#{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: #(NSUTF8StringEncoding)}
documentAttributes:nil error:nil];
Name: NSRangeException
Reason: *** -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2]
Stack:
0
CoreFoundation 0x0000000183a0c2d8 __exceptionPreprocess + 128
1
libobjc.A.dylib 0x00000001952380e4 objc_exception_throw + 56
2
CoreFoundation 0x00000001838ef85c -[__NSArrayM objectAtIndex:] + 260
3
UIKit 0x0000000188575a94 -[UITableView cellForRowAtIndexPath:] + 212
4
UIKit 0x000000018873fa00 -[UITableViewWrapperView gestureRecognizerShouldBegin:] + 284
5
UIKit 0x00000001885e2c34 -[UIGestureRecognizer _shouldBegin] + 1072
6
UIKit 0x000000018847b340 -[UIGestureRecognizer setState:] + 428
7
UIKit 0x00000001885f4fdc -[UIScrollViewPanGestureRecognizer touchesMoved:withEvent:] + 100
8
UIKit 0x000000018847a6d8 -[UIWindow _sendGesturesForEvent:] + 592
9
UIKit 0x0000000188479f50 -[UIWindow sendEvent:] + 656
10
UIKit 0x000000018844d18c -[UIApplication sendEvent:] + 260
11
UIKit 0x00000001886ee324 _UIApplicationHandleEventFromQueueEvent + 15420
12
UIKit 0x000000018844b6a0 _UIApplicationHandleEventQueue + 1712
13
CoreFoundation 0x00000001839c4240 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 20
14
CoreFoundation 0x00000001839c359c __CFRunLoopDoSources0 + 444
15
CoreFoundation 0x00000001839c1594 __CFRunLoopRun + 708
16
CoreFoundation 0x00000001838ed2d4 CFRunLoopRunSpecific + 392
17
UIFoundation 0x0000000191850c10 -[NSHTMLReader _loadUsingWebKit] + 1984
18
UIFoundation 0x0000000191851fd0 -[NSHTMLReader attributedString] + 28
19
UIFoundation 0x00000001917ef23c _NSReadAttributedStringFromURLOrData + 5800
20
UIFoundation 0x00000001917edad8 -[NSAttributedString(NSAttributedStringUIFoundationAdditions) initWithData:options:documentAttributes:error:] + 144
21
XXApp 0x0000000100129fb0 -[NSString(XXFormat) attributedStringFromHTMLByFont:] (NSString+XXFormat.m:15)
22
XXApp 0x0000000100112f64 -[XXNews(Peer) attributedContent] (XXNews+Peer.m:56)
23
XXApp 0x00000001000fc854 -[XXWidgetNewsCell setWidget:] (XXWidgetNewsCell.m:53)
24
XXApp 0x0000000100116ba4 -[XXTimeLineTableViewController tableView:cellForRowAtIndexPath:] (XXTimeLineTableViewController.m:231)
25
UIKit 0x000000018874da68 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 540
26
UIKit 0x0000000188741890 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2360
27
UIKit 0x000000018852d268 -[UITableView layoutSubviews] + 168
28
UIKit 0x0000000188449760 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 576
29
QuartzCore 0x0000000187d91e1c -[CALayer layoutSublayers] + 148
30
QuartzCore 0x0000000187d8c884 CA::Layer::layout_if_needed() + 316
31
QuartzCore 0x0000000187d8c728 CA::Layer::layout_and_display_if_needed() + 28
32
QuartzCore 0x0000000187d8bebc CA::Context::commit_transaction() + 272
33
QuartzCore 0x0000000187d8bc3c CA::Transaction::commit() + 524
34
QuartzCore 0x0000000187d85364 CA::Transaction::observer_callback() + 76
35
CoreFoundation 0x00000001839c42a4 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 28
36
CoreFoundation 0x00000001839c1230 __CFRunLoopDoObservers + 356
37
CoreFoundation 0x00000001839c1610 __CFRunLoopRun + 832
38
CoreFoundation 0x00000001838ed2d4 CFRunLoopRunSpecific + 392
39
GraphicsServices 0x000000018d1036fc GSEventRunModal + 164
40
UIKit 0x00000001884b2fac UIApplicationMain + 1484
41
XXApp 0x0000000100101280 main (main.m:14)
42
libdyld.dylib 0x00000001958b6a08 start + 0
It's not the snippet that you have shared here that is causing the issue but you are trying to access to in-existent element in an array :
Name: NSRangeException
Reason: *** -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2]
the array has bounds [0 .. 2] and you try to access to index 3 that's not existent element
make sure in your method cellForRowAtIndexPath you are not bypassing the index of your NSArray

Resources