What characters are allowed in a iOS file name?

后端 未结 9 2065
长情又很酷
长情又很酷 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 06:01

    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.

    Swift 3 & 4

    var invalidCharacters = CharacterSet(charactersIn: ":/")
    invalidCharacters.formUnion(.newlines)
    invalidCharacters.formUnion(.illegalCharacters)
    invalidCharacters.formUnion(.controlCharacters)
    
    let newFilename = originalFilename
        .components(separatedBy: invalidCharacters)
        .joined(separator: "")
    

    Swift 2

    let invalidCharacters = NSMutableCharacterSet(charactersInString: ":/")
    invalidCharacters.formUnionWithCharacterSet(NSCharacterSet.newlineCharacterSet())
    invalidCharacters.formUnionWithCharacterSet(NSCharacterSet.illegalCharacterSet())
    invalidCharacters.formUnionWithCharacterSet(NSCharacterSet.controlCharacterSet())
    
    let filename = originalFilename
        .componentsSeparatedByCharactersInSet(invalidCharacters)
        .joinWithSeparator("")
    

提交回复
热议问题