问题
I have a hashtags resolver UITextView extension that turns any word with "#" before it to a tappable blue link. It is working fine except when tapping on Arabic hashtags.
extension UITextView {
func resolveHashAndMentionTags(){
// turn string in to NSString
let nsText:NSString = self.text as NSString
// this needs to be an array of NSString. String does not work.
let words:[NSString] = nsText.components(separatedBy: " ") as [NSString]
// you can't set the font size in the storyboard anymore, since it gets overridden here.
let attrs = [
NSAttributedStringKey.font : UIFont(name: "Avenir-Light", size: 14.0)!//UIFont.systemFont(ofSize: 13.0)
]
// you can staple URLs onto attributed strings
let attrString = NSMutableAttributedString(string: nsText as String, attributes:attrs)
// tag each word if it has a hashtag or mention
for word in words {
// found a word that is prepended by a hashtag!
if word.hasPrefix("#") {
// a range is the character position, followed by how many characters are in the word.
// we need this because we staple the "href" to this range.
let matchRange:NSRange = nsText.range(of: word as String)
// convert the word from NSString to String
// this allows us to call "dropFirst" to remove the hashtag
var stringifiedWord:String = word as String
// drop the hashtag
stringifiedWord = String(stringifiedWord.dropFirst())
print(stringifiedWord)
attrString.addAttribute(NSAttributedStringKey.link, value: "hash://\(stringifiedWord)", range: matchRange)
// }
} else if word.hasPrefix("@") {
// a range is the character position, followed by how many characters are in the word.
// we need this because we staple the "href" to this range.
let matchRange:NSRange = nsText.range(of: word as String)
// convert the word from NSString to String
// this allows us to call "dropFirst" to remove the mention@
var stringifiedWord:String = word as String
// drop the hashtag
stringifiedWord = String(stringifiedWord.dropFirst())
attrString.addAttribute(NSAttributedStringKey.link, value: "mention://\(stringifiedWord)", range: matchRange)
// }
}
}
// we're used to textView.text
// but here we use textView.attributedText
// again, this will also wipe out any fonts and colors from the storyboard,
// so remember to re-add them in the attrs dictionary above
self.attributedText = attrString
}
Then in my posts cell i call the UITextViewDelegate
function.
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
let path = URL.absoluteString
switch URL.scheme! {
case "hash" :
let hash = path.removingPercentEncoding?.components(separatedBy: "://").last
print(hash!) // ---> Retriving tapped on hash name correctly
delegate?.hashTableViewCell(self, shouldSelectTag: hash!)
case "mention" :
let mention = path.removingPercentEncoding?.components(separatedBy: "://").last
print(mention!) // ---> Retriving tapped on mention name correctly
delegate?.mentionTableViewCell(self, shouldSelectTag: mention!, userId: nil)
default:
print("Just a regular link \(path.removingPercentEncoding!)")
}
return true
}
As i mentioned above the code it is working fine for english letters but when tapping on an arabic hashtag or mention it crashes in the AppDelegate
.
Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1030fcb94)
I tried to debug with break points to know where the error is exactly but actually i found out that it is crashing even before entering the UITextViewDelegate
function. So now i have no clue at all where the error could be exactly.
Maybe there could be some kind of an issue with arabic letters being used as a link in a UITextView
?
Here is the stack trace.
- thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BREAKPOINT (code=1, subcode=0x1030fcb94) frame #0: 0x00000001030fcb94 libswiftFoundation.dylib
function signature specialization <Arg[0] = Owned To Guaranteed, Arg[1] = Dead> of static Foundation.URL._unconditionallyBridgeFromObjectiveC(Swift.Optional<__ObjC.NSURL>) -> Foundation.URL + 288 frame #1: 0x0000000103045f24 libswiftFoundation.dylib
static Foundation.URL._unconditionallyBridgeFromObjectiveC(Swift.Optional<__ObjC.NSURL>) -> Foundation.URL + 20 frame #2: 0x0000000101199c68 OOL@objc PostTableViewCell.textView(_:shouldInteractWith:in:) at PostTableViewCell.swift:0 frame #3: 0x000000018e1e397c UIKit
-[_UITextViewInteractableLink allowInteraction:] + 360 frame #4: 0x000000018e1e2698 UIKit-[_UITextViewInteractableItem handleTap] + 40 frame #5: 0x000000018db64548 UIKit
-[UITextGestureClusterLinkInteract smallDelayRecognizer:] + 296 frame #6: 0x000000018db7ccd0 UIKit-[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:] + 64 frame #7: 0x000000018db812c4 UIKit
_UIGestureRecognizerSendTargetActions + 124 frame #8: 0x000000018d659aa8 UIKit_UIGestureRecognizerSendActions + 320 frame #9: 0x000000018d510c38 UIKit
-[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 732 frame #10: 0x000000018db6ab34 UIKit_UIGestureEnvironmentUpdate + 1084 frame #11: 0x000000018db6a6a4 UIKit
-[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] + 404 frame #12: 0x000000018db69800 UIKit-[UIGestureEnvironment _updateGesturesForEvent:window:] + 276 frame #13: 0x000000018d50ef44 UIKit
-[UIWindow sendEvent:] + 3180 frame #14: 0x000000018d4dff64 UIKit-[UIApplication sendEvent:] + 340 frame #15: 0x000000018de3531c UIKit
__dispatchPreprocessedEventFromEventQueue + 2364 frame #16: 0x000000018de378a8 UIKit__handleEventQueueInternal + 4760 frame #17: 0x000000018de307c0 UIKit
__handleHIDEventFetcherDrain + 152 frame #18: 0x0000000183fa697c CoreFoundation__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24 frame #19: 0x0000000183fa68fc CoreFoundation
__CFRunLoopDoSource0 + 88 frame #20: 0x0000000183fa6184 CoreFoundation__CFRunLoopDoSources0 + 204 frame #21: 0x0000000183fa3d5c CoreFoundation
__CFRunLoopRun + 1048 frame #22: 0x0000000183ec3e58 CoreFoundationCFRunLoopRunSpecific + 436 frame #23: 0x0000000185d70f84 GraphicsServices
GSEventRunModal + 100 frame #24: 0x000000018d54367c UIKit`UIApplicationMain + 236
- frame #25: 0x0000000101063348 OOL
main at AppDelegate.swift:22 frame #26: 0x00000001839e056c libdyld.dylib
start + 4
回答1:
What I guess could be the issue (either on tag or hash)...
You do:
attrString.addAttribute(NSAttributedStringKey.link, value: "hash://\(stringifiedWord)", range: matchRange)
But if you'd use a URL
object (let url = URL.init(string:"hash://\(stringifiedWord)")
) you'll see it may be nil
in case of invalid string url and in your case arabic characters seem to be invalid.
The delegate method func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool
is giving a URL
object in parameters, and because your method is not called when you don't have a valid url, I guess that inner line in Apple's code assume it's a valid url, doesn't check it and crashes. That would explain why your method isn't called and crash before entering yours.
Solution: Use percent escaped characters.
Instead of putting value: "hash://\(stringifiedWord)"
, do value: "hash://\(stringifiedWord.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))"
or other character set allowed.
In the delegate method you are already removing the percent escape: let hash = path.removingPercentEncoding?.components(separatedBy: "://").last
so you don't have to add anything there.
Additional note:
You are doing if word.hasPrefix("#")
and `if word.hasPrefix("@") almost the same thing (just the scheme change), you could simplify/factorize that, sample code not tested:
let dict = ["#":"mention://", "@": "hash://"]
for (key, value) in dict
{
if word.hasPrefix(key)
{
let matchRange:NSRange = nsText.range(of: word as String)
var stringifiedWord:String = word as String
stringifiedWord = String(stringifiedWord.dropFirst(key.count))
let espcapedWord = stringifiedWord.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed
let stringURL = "\(value)\(escapedWord)"
if let url = URL.init(string:stringURL) //That should you avoid any crash just in case
{
attrString.addAttribute(.link, value: stringURL, range: matchRange)
}
else
{
print("Oooops with \(stringifiedWord) invalid URL: \(stringURL)")
}
}
}
来源:https://stackoverflow.com/questions/48154641/hashtags-in-arabic-language-crashes-the-app