Last active
April 26, 2024 02:21
-
-
Save iGranDav/8a507eb9314391338507 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension UIDevice { | |
/** | |
Try to get the username from the device name using common knows | |
default device names format. | |
- copyright: Owen Godfrey on [StackOverflow](http://stackoverflow.com/questions/8261961/better-way-to-get-the-users-name-from-device) | |
- remark: Original regexpr improved to support custom name with model included eg. `<username>'s iPhone 6S` | |
- returns: Username found or the device name itself as default value | |
*/ | |
func username() -> String { | |
let deviceName = self.name | |
let expression = "^(?:iPhone|phone|iPad|iPod)\\s+(?:de\\s+)?(?:[1-9]?S?\\s+)?|(\\S+?)(?:['']?s)?(?:\\s+(?:iPhone|phone|iPad|iPod)\\s+(?:[1-9]?S?\\s+)?)?$|(\\S+?)(?:['']?的)?(?:\\s*(?:iPhone|phone|iPad|iPod))?$|(\\S+)\\s+" | |
var username = deviceName | |
do { | |
let regex = try NSRegularExpression(pattern: expression, options: .CaseInsensitive) | |
let matches = regex.matchesInString(deviceName as String, | |
options: NSMatchingOptions.init(rawValue: 0), | |
range: NSMakeRange(0, deviceName.characters.count)) | |
let rangeNotFound = NSMakeRange(NSNotFound, 0) | |
var nameParts = [String]() | |
for result in matches { | |
for i in 1..<result.numberOfRanges { | |
if !NSEqualRanges(result.rangeAtIndex(i), rangeNotFound) { | |
nameParts.append((deviceName as NSString).substringWithRange(result.rangeAtIndex(i)).capitalizedString) | |
} | |
} | |
} | |
if nameParts.count > 0 { | |
username = nameParts.joinWithSeparator(" ") | |
} | |
} | |
catch { NSLog("[Error] While searching for username from device name") } | |
return username | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @wingovers for your work on this 👍