Skip to content

Instantly share code, notes, and snippets.

@johndpope
Forked from AhmedOS/PushIDGenerator.swift
Created October 23, 2020 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johndpope/886783fe5fe49a20ef65050423124a37 to your computer and use it in GitHub Desktop.
Save johndpope/886783fe5fe49a20ef65050423124a37 to your computer and use it in GitHub Desktop.
Swift 4 port of Firebase Push ID generator
// original: https://gist.github.com/mikelehen/3596a30bd69384624c11
class PushIDGenerator {
private init() { }
static private let PUSH_CHARS = Array("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz")
static private var lastPushTime: UInt64 = 0
static private var lastRandChars = Array<Int>(repeating: 0, count: 12)
static func generate() -> String {
var now = UInt64(NSDate().timeIntervalSince1970 * 1000)
let duplicateTime = (now == lastPushTime)
lastPushTime = now
var timeStampChars = Array<Character>(repeating: PUSH_CHARS.first!, count: 8)
for i in stride(from: 7, through: 0, by: -1) {
timeStampChars[i] = PUSH_CHARS[Int(now % 64)]
now >>= 6
}
assert(now == 0, "We should have converted the entire timestamp.")
var id = String(timeStampChars)
if !duplicateTime {
for i in 0..<12 {
lastRandChars[i] = Int(floor(Double.random(in: 0..<1) * 64))
}
}
else {
var i = 11
while i >= 0 && lastRandChars[i] == 63 {
lastRandChars[i] = 0
i -= 1
}
lastRandChars[i] += 1
}
for i in 0..<12 {
id.append(PUSH_CHARS[lastRandChars[i]])
}
assert(id.count == 20, "Length should be 20.")
return id
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment