Last active
January 7, 2020 07:45
-
-
Save Tron5000/7bb51318db1da86a3a78 to your computer and use it in GitHub Desktop.
Compressing/Decompressing UUID to 22 characters via base64
This file contains 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 | |
// 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. | |
guard let shortenedIdentifier = shortenedIdentifier else { | |
return nil | |
} | |
// Rehydrate the shortenedIdentifier | |
let shortenedIdentifierWithDoubleEquals = shortenedIdentifier + base64TailBuffer + base64TailBuffer | |
let data = Data(base64Encoded: shortenedIdentifierWithDoubleEquals) | |
let uuidBytes = data?.withUnsafeBytes { $0.baseAddress?.assumingMemoryBound(to: UInt8.self) } | |
let tempUuid = NSUUID(uuidBytes: uuidBytes) | |
return tempUuid.uuidString | |
} | |
let testCompress = compress(identifier: identifier) | |
let testRehydrate = rehydrate(shortenedIdentifier: testCompress) |
I've updated again for Swift 3 and Xcode 8.
I've updated for Swift 5 and Xcode 10.2.1.
Is there a way to avoid special characters?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good catch - thanks! I've updated the playground for Xcode 7.2.