-
-
Save jurgenizer/6612ab98b4a242d944c3460d23f17f78 to your computer and use it in GitHub Desktop.
Updated for Swift 3
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 | |
import UIKit | |
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 | |
/* regex from original gist | |
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+" | |
*/ | |
//I prefer this regex | |
let expression = "^(?:iPhone|phone|iPad|iPod)\\s+(?:de\\s+)?|(\\S+?)(?:['’]?s)?(?:\\s+(?:iPhone|phone|iPad|iPod))?$|(\\S+?)(?:['’]?的)?(?:\\s*(?:iPhone|phone|iPad|iPod))?$|(\\S+)\\s+" | |
var username = deviceName | |
do { | |
let regex = try NSRegularExpression(pattern: expression, options: .caseInsensitive) | |
let matches = regex.matches(in: deviceName as String, | |
options: NSRegularExpression.MatchingOptions.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.rangeAt(i), rangeNotFound) { | |
nameParts.append((deviceName as NSString).substring(with: result.rangeAt(i)).capitalized) | |
} | |
} | |
} | |
if nameParts.count > 0 { | |
username = nameParts.joined(separator: " ") | |
} | |
} | |
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