NSFileManager unique file names

前端 未结 9 1955
生来不讨喜
生来不讨喜 2020-12-23 10:54

I need a quick and easy way to store files with unique file names on iOS. I need to prefix the file with a string, and then append the generated unique identifier to the en

9条回答
  •  心在旅途
    2020-12-23 11:41

    Swift 4.2, I use two options, one mostly unique but readable, and the other just unique.

    // Create a unique filename, added to a starting string or not
    public func uniqueFilename(filename: String = "") -> String {
        let uniqueString = ProcessInfo.processInfo.globallyUniqueString
        return filename + "-" + uniqueString
    }
    
    // Mostly Unique but Readable ID based on date and time that is URL compatible ("unique" to nearest second)
    public func uniqueReadableID(name: String = "") -> String {
    
        let timenow = DateFormatter.localizedString(from: Date(), dateStyle: .medium, timeStyle: .medium)
        let firstName = name + "-" + timenow
        do {
            // Make ID compatible with URL usage
            let regex = try NSRegularExpression(pattern: "[^a-zA-Z0-9_]+", options: [])
            let newName = regex.stringByReplacingMatches(in: firstName, options: [], range: NSMakeRange(0, firstName.count), withTemplate: "-")
            return newName
        }
        catch {
            print("

提交回复
热议问题