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 wondering if I'm doing it right.
NSString *filename = @"A file name"; fileName = [fileName stringByTrimmingCharactersInSet: [NSCharacterSet controlCharacterSet]]; fileName = [fileName stringByTrimmingCharactersInSet: [NSCharacterSet newlineCharacterSet]];
I'm also wondering if there's already a method that validates a string as a file name.
Thank you for your advice!
Supported characters for a file name are letters, numbers, spaces, and ( ) _ - , . *Please note file names should be limited to 100 characters. Characters that are NOT supported include, but are not limited to: @ $ % & \ / : * ? " ' < > | ~ ` # ^ + = { } [ ] ; !
The names of files and folders in Mac OS X can use almost any character out of thousands of Unicode characters, which include symbols, arrows, and icons as well. There are only two characters you can't use: one is the colon (because it's used by the system).
Valid Special Characters for File and Folder NamesSpecial characters are symbols such as & (ampersand) or * (asterisk). Some require a shift key stroke, such as the special characters grouped in the number keys, while others do not, such as / (forward slash).
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:@"-"];
I find this to be cleaner and probably much more performant. This is based on Angel Naydenov's solution, but first constructing Character set with all invalid characters and then calling components(separatedBy:)
just once.
var invalidCharacters = CharacterSet(charactersIn: ":/") invalidCharacters.formUnion(.newlines) invalidCharacters.formUnion(.illegalCharacters) invalidCharacters.formUnion(.controlCharacters) let newFilename = originalFilename .components(separatedBy: invalidCharacters) .joined(separator: "")
let invalidCharacters = NSMutableCharacterSet(charactersInString: ":/") invalidCharacters.formUnionWithCharacterSet(NSCharacterSet.newlineCharacterSet()) invalidCharacters.formUnionWithCharacterSet(NSCharacterSet.illegalCharacterSet()) invalidCharacters.formUnionWithCharacterSet(NSCharacterSet.controlCharacterSet()) let filename = originalFilename .componentsSeparatedByCharactersInSet(invalidCharacters) .joinWithSeparator("")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With