How to make an NSString path (file name) safe

后端 未结 7 716
陌清茗
陌清茗 2021-02-01 01:52

I\'m using very tricky fighting methods :) to make a string like Fi?le*/ Name safe for using as a file name like File_Name. I\'m sure there is a cocoa

7条回答
  •  时光说笑
    2021-02-01 02:13

    I iterated on johnboiles's answer, converting to Swift, and writing it as an extension:

    extension String {
        var stringForFilePath: String {
            // characterSet contains all illegal characters on OS X and Windows
            let characterSet = NSCharacterSet(charactersInString: "\"\\/?<>:*|")
            // replace "-" with character of choice
            return componentsSeparatedByCharactersInSet(characterSet).joinWithSeparator("-")
        }
    }
    

    Illegal character set referenced from here.

提交回复
热议问题