从 NSString 创建安全文件名?
有没有办法获取 NSString 并将其转换为安全版本,可以用作文件名保存到 iPhone 上的用户文档目录中。
我目前正在做这样的事情:
NSString *inputString = @"This is sample text which may have funny chars and spaces in.";
NSInteger len = [inputString length];
NSString *newFilename = [[inputString substringToIndex:MIN(20, len)] stringByAppendingPathExtension:@"txt"];
这目前给我留下了类似的东西:
This is sample text .txt
需要确保文件名中不允许的字符也被删除。
Is there way to take a NSString and turn it into a safe version that can be used as a filename to save to the user Documents directory on the iPhone.
I'm currently doing something like this:
NSString *inputString = @"This is sample text which may have funny chars and spaces in.";
NSInteger len = [inputString length];
NSString *newFilename = [[inputString substringToIndex:MIN(20, len)] stringByAppendingPathExtension:@"txt"];
This currently leaves me with something like:
This is sample text .txt
Need to make sure characters that are not allowed in filenames and stripped out too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可能最终会得到一些正则表达式或其他东西。仅仅是因为使用
except
过滤器太危险了(您可能会错过一些非法字符)。因此,我建议您使用 RegexKitLite (http://regexkit.sourceforge.net/RegexKitLite/),并结合以下代码行:
这将替换除 AZ、az 和 0-9 =) 之外的所有字符!
You'll probably end up with some regex or something. Simply because it's too dangerous to use a
except
-filter (you may miss some illegal chars).Therefor I'ld recommend you to use RegexKitLite (http://regexkit.sourceforge.net/RegexKitLite/), combined with the following line of code:
This will replace all characters except A-Z, a-z and 0-9 =)!
您也可以用老式的方式来代替使用正则表达式:
You can also do it the old fashioned way instead of using a regex:
如果您真正需要的只是一个安全的随机文件名,那么只需使用 SecRandomCopyBytes 达到您想要的长度并对其进行 base64 编码即可。
If all you really need is a safely random filename then just use SecRandomCopyBytes to the length you want and base64-encode it.