Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

ios - Hashtags in Arabic language crashes the app

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.dylibfunction 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.dylibstatic 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 GraphicsServicesGSEventRunModal + 100 frame #24: 0x000000018d54367c UIKit`UIApplicationMain + 236
    • frame #25: 0x0000000101063348 OOLmain at AppDelegate.swift:22 frame #26: 0x00000001839e056c libdyld.dylibstart + 4
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)")
       }
   }
}

Edit: Depending on the iOS version (tested on Simulator), it could make it crash, or simply not call the delegate method because of the invalid URL.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...