Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save drinkius/7a497f25aaa54963de2c1269f77627d4 to your computer and use it in GitHub Desktop.
Save drinkius/7a497f25aaa54963de2c1269f77627d4 to your computer and use it in GitHub Desktop.
Compressing/Decompressing UUID to 22 characters via base64
import Foundation
// Compressing and decompressing a UUID to 22 characters via base64.
// Works great as a Swift playground. These articles were helpful:
// http://blog.codinghorror.com/equipping-our-ascii-armor/
// http://69.195.124.60/~jasondoh/2013/08/14/creating-a-short-guid-in-objective-c/
let identifier = NSUUID().uuidString
let base64TailBuffer = "="
func compress(identifier: String) -> String? {
guard let tempUuid = NSUUID(uuidString: identifier) else { return nil }
var tempUuidBytes: UInt8 = 0
tempUuid.getBytes(&tempUuidBytes)
let data = Data(bytes: &tempUuidBytes, count: 16)
let base64 = data.base64EncodedString(options: NSData.Base64EncodingOptions())
return base64.replacingOccurrences(of: base64TailBuffer, with: "")
}
func rehydrate(shortenedIdentifier: String?) -> String? {
// Expand an identifier out of a CBAdvertisementDataLocalNameKey or service characteristic.
if shortenedIdentifier == nil {
return nil
}
else {
// Rehydrate the shortenedIdentifier
let shortenedIdentifierWithDoubleEquals = shortenedIdentifier! + base64TailBuffer + base64TailBuffer
let data = Data(base64Encoded: shortenedIdentifierWithDoubleEquals, options: Data.Base64DecodingOptions())
let tempUuid = NSUUID(uuidBytes: data?.withUnsafeBytes({ UnsafePointer<UInt8>($0) }))
return tempUuid.uuidString
}
}
let testCompress = compress(identifier: identifier)
let testRehydrate = rehydrate(shortenedIdentifier: testCompress)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment