我正在寻找Swift等效的以下Objective C公共代码.在Objective C中,我们将以下内容重定向到文档文件夹而不是控制台:
- (void) redirectConsoleLogToDocumentFolder { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@"console.log"]; freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr); }
如何在Swift 2中完成?
我建议阅读有关登录swift的信息
func redirectConsoleLogToDocumentFolder() { var paths: NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) var documentsDirectory: NSString = paths[0] var logPath: NSString = documentsDirectory.stringByAppendingPathComponent("console.log") var cstr = (logPath as NSString).UTF8String freopen(cstr, "a+", stderr) }
Swift 3.0的更新答案
if let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first { let documentsDirectory = NSURL(fileURLWithPath: path) let logPath = documentsDirectory.appendingPathComponent("console.log")! freopen(logPath.absoluteString, "a+", stderr) }