NSFileManager unique file names

前端 未结 9 1890
生来不讨喜
生来不讨喜 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:30

    You can also use the venerable mktemp() (see man 3 mktemp). Like this:

    - (NSString*)createTempFileNameInDirectory:(NSString*)dir
    {
      NSString* templateStr = [NSString stringWithFormat:@"%@/filename-XXXXX", dir];
      char template[templateStr.length + 1];
      strcpy(template, [templateStr cStringUsingEncoding:NSASCIIStringEncoding]);
      char* filename = mktemp(template);
    
      if (filename == NULL) {
        NSLog(@"Could not create file in directory %@", dir);
        return nil;
      }
      return [NSString stringWithCString:filename encoding:NSASCIIStringEncoding];
    }
    

    The XXXXX will be replaced with a unique letter/number combination. They can only appear at the end of the template, so you cannot have an extension appended in the template (though you can append it after the unique file name is obtained). Add as many X as you want in the template.

    The file is not created, you need to create it yourself. If you have multiple threads creating unique files in the same directory, you run the possibility of having race conditions. If this is the case, use mkstemp() which creates the file and returns a file descriptor.

    0 讨论(0)
  • 2020-12-23 11:31

    Here is what I ended up using in Swift 3.0

    public func generateUniqueFilename (myFileName: String) -> String {
    
        let guid = ProcessInfo.processInfo.globallyUniqueString
        let uniqueFileName = ("\(myFileName)_\(guid)")
    
        print("uniqueFileName: \(uniqueFileName)")
    
        return uniqueFileName
    }
    
    0 讨论(0)
  • 2020-12-23 11:33

    Swift 4.1 and 5. Just pass you file extension name and function will return unique file name.

    func uniqueFileNameWithExtention(fileExtension: String) -> String {
            let uniqueString: String = ProcessInfo.processInfo.globallyUniqueString
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyyMMddhhmmsss"
            let dateString: String = formatter.string(from: Date())
            let uniqueName: String = "\(uniqueString)_\(dateString)"
            if fileExtension.length > 0 {
                let fileName: String = "\(uniqueName).\(fileExtension)"
                return fileName
            }
            
            return uniqueName
        }
    
    0 讨论(0)
  • 2020-12-23 11:37

    I use current date to generate random file name with a given extension. This is one of the methods in my NSFileManager category:

    + (NSString*)generateFileNameWithExtension:(NSString *)extensionString
    {
        // Extenstion string is like @".png"
    
        NSDate *time = [NSDate date];
        NSDateFormatter* df = [NSDateFormatter new];
        [df setDateFormat:@"dd-MM-yyyy-hh-mm-ss"];
        NSString *timeString = [df stringFromDate:time];
        NSString *fileName = [NSString stringWithFormat:@"File-%@%@", timeString, extensionString];
    
        return fileName;
    }
    
    0 讨论(0)
  • 2020-12-23 11:41

    In iOS 6 the simplest method is to use:

    NSString *uuidString = [[NSUUID UUID] UUIDString];
    
    0 讨论(0)
  • 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("                                                                    
    0 讨论(0)
提交回复
热议问题