Guest User

ActiveType.swift

a guest
Dec 17th, 2015
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.98 KB | None | 0 0
  1. //
  2. //  ActiveType.swift
  3. //  ActiveLabel
  4. //
  5. //  Created by Johannes Schickling on 9/4/15.
  6. //  Copyright © 2015 Optonaut. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10.  
  11. enum ActiveElement {
  12.     case Mention(String)
  13.     case Hashtag(String)
  14.     case URL(NSURL)
  15.     case None
  16. }
  17.  
  18. enum ActiveType {
  19.     case Mention
  20.     case Hashtag
  21.     case URL
  22.     case None
  23. }
  24.  
  25. func activeElement(word: String) -> ActiveElement {
  26.     if let url = reduceRightToURL(word) {
  27.         return .URL(url)
  28.     }
  29.    
  30.     if word.characters.count < 2 {
  31.         return .None
  32.     }
  33.    
  34.     // remove # or @ sign and reduce to alpha numeric string (also allowed: _)
  35.     guard let allowedWord = reduceRightToAllowed(word.substringFromIndex(word.startIndex.advancedBy(1))) else {
  36.         return .None
  37.     }
  38.    
  39.     if word.hasPrefix("@") {
  40.         return .Mention(allowedWord)
  41.     } else if word.hasPrefix("#") {
  42.         return .Hashtag(allowedWord)
  43.     } else {
  44.         return .None
  45.     }
  46. }
  47.  
  48. private func reduceRightToURL(str: String) -> NSURL? {
  49.     if let regex = try? NSRegularExpression(pattern: "(?i)https?://(?:www\\.)?\\S+(?:/|\\b)", options: [.CaseInsensitive]) {
  50.         let nsStr = str as NSString
  51.         let results = regex.matchesInString(str, options: [], range: NSRange(location: 0, length: nsStr.length))
  52.         if let result = results.map({ nsStr.substringWithRange($0.range) }).first, url = NSURL(string: result) {
  53.             return url
  54.         }
  55.     }
  56.     return nil
  57. }
  58.  
  59. private func reduceRightToAllowed(str: String) -> String? {
  60.     if let regex = try? NSRegularExpression(pattern: "^[a-z0-9_]*", options: [.CaseInsensitive]) {
  61.         let nsStr = str as NSString
  62.         let results = regex.matchesInString(str, options: [], range: NSRange(location: 0, length: nsStr.length))
  63.         if let result = results.map({ nsStr.substringWithRange($0.range) }).first {
  64.             if !result.isEmpty {
  65.                 return result
  66.             }
  67.         }
  68.     }
  69.     return nil
  70. }
Add Comment
Please, Sign In to add comment