What characters are allowed in a iOS file name?

后端 未结 9 2136
长情又很酷
长情又很酷 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: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)
    

提交回复
热议问题