What characters are allowed in a iOS file name?

后端 未结 9 2108
长情又很酷
长情又很酷 2020-12-29 05:20

I\'m looking for a way to make sure a string can be used as a file name under iOS. I\'m currently in the section of the code that deletes incompatible characters. I\'m wonde

相关标签:
9条回答
  • 2020-12-29 05:49

    Use RegEx:

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^a-zA-Z0-9_]+" options:0 error:nil];
    filename = [regex stringByReplacingMatchesInString:filename options:0 range:NSMakeRange(0, filename.length) withTemplate:@"-"];
    
    0 讨论(0)
  • 2020-12-29 05:51

    I've had to save remote files locally with filenames containing other characters than basic alpha-numeric characters. I use the method below to strip out potential invalid characters, ensuring it's a valid filename for the filesystem when generating a NSURL using URLWithString:

        filename = [[filename componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString:@"" ];
        filename = [[filename componentsSeparatedByCharactersInSet:[NSCharacterSet illegalCharacterSet]] componentsJoinedByString:@"" ];
        filename = [[filename componentsSeparatedByCharactersInSet:[NSCharacterSet symbolCharacterSet]] componentsJoinedByString:@"" ];
        fileURLString = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
        fileURL = [NSURL URLWithString:fileURLString];
    

    You may also want to test for collision errors first using:

        [[NSFileManager defaultManager] fileExistsAtPath:[fileURL absoluteString]]
    
    0 讨论(0)
  • 2020-12-29 05:56

    I'm pretty happy with this solution:

    NSString *testString = @"This*is::/legal.                                                                    
    0 讨论(0)
  • 2020-12-29 05:59

    I came up with the following solution. Works nice so far.

    import Foundation
    
    extension String {
        func removeUnsupportedCharactersForFileName() -> String {
            var cleanString = self
            ["?", "/", "\\", "*"].forEach {
                cleanString = cleanString.replacingOccurrences(of: $0, with: "-")
            }
            return cleanString
        }
    }
    
    let a = "***???foo.png"
    let validString = a.removeUnsupportedCharactersForFileName()
    
    0 讨论(0)
  • 2020-12-29 06:00

    As I did not see a list with allowed characters in this question but the question wanted a list with such characters I am adding a bit more details on this topic.

    First we need to know what is the file system that iOS devices use. Using multiple online sources this seems to be HFSX which is the HFS+ case sensitive version. And including one link here for reference: https://apple.stackexchange.com/questions/83671/what-filesystem-does-ios-use

    Now that we know what the file system is we can look for what characters are not allowed. And these seem to be: colon (:) and slash (/). Here is a link for reference: http://www.comentum.com/File-Systems-HFS-FAT-UFS.html

    Having this information and what others have written in this thread my personal preference for removing not allowed characters from file names is the following Swift code:

    filename = "-".join(filename.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()))
    filename = "-".join(filename.componentsSeparatedByCharactersInSet(NSCharacterSet.illegalCharacterSet()))
    filename = "-".join(filename.componentsSeparatedByCharactersInSet(NSCharacterSet.controlCharacterSet()))
    filename = "-".join(filename.componentsSeparatedByString(":"))
    filename = "-".join(filename.componentsSeparatedByString("/"))
    

    The reason I am not preferring the RegEx approach is that it seems too restrictive to me. I do not want to restrict my users only to Latin characters. They may as well wish to use some Chinese, Cyrillic or whatever else they like.

    Happy coding!

    0 讨论(0)
  • 2020-12-29 06:00

    Base on Marian Answers, here is a string extension to remove any unwanted characters.

    extension String {
    
    func stripCharacters() -> String {
        var invalidCharacters = CharacterSet(charactersIn: ":/")
        invalidCharacters.formUnion(.newlines)
        invalidCharacters.formUnion(.illegalCharacters)
        invalidCharacters.formUnion(.controlCharacters)
    
        let newString = self
            .components(separatedBy: invalidCharacters)
            .joined(separator: "_")
    
        return newString
       }
    }
    
    Example:
    let fileName = "Man(lop23/45"
    let newFileName = fileName.stripCharacters()
    print(newFileName)
    
    0 讨论(0)
提交回复
热议问题