[英]why am I not getting the correct URL path in swift OSX
this is the objective c code 这是目标C代码
dispatch_once(&onceToken, ^{
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYYMMDDHHmmss"];
homeDir = [NSURL fileURLWithPath:[@"~/xyz/" stringByExpandingTildeInPath]];
});
NSString* date = [formatter stringFromDate:[NSDate date]];
self.file = [[homeDir URLByAppendingPathComponent:[@"xyz-" stringByAppendingString:date]] URLByAppendingPathExtension:@"m4a"];
NSLog(@" self.file = %@", self.file );
when I tried to convert this code to SWIFT 3, I am not getting the correct URL.. Can anyone help? 当我尝试将此代码转换为SWIFT 3时,我没有获得正确的URL。有人可以帮忙吗?
This is the path I get
~/xyz/xyz-201710291142410.m4a -- file:///Users/xyz/Library/Developer/Xcode/DerivedData/xyz-guhahcdeflytfhhdsxtsrucmqqnv/Build/Products/Debug/
But this is the path I want 但这是我想要的路
file:///Users/xyz/xyz/xyz-201710291142410..m4a 文件:///Users/xyz/xyz/xyz-201710291142410..m4a
my failed swift syntax 我失败的快速语法
formatter = DateFormatter() 格式化程序= DateFormatter()
formatter?.dateFormat = "YYYYMMDDHHmmss"
let urlS = "~/xyz/"
// NSURL.fileURL(withPath: urlS.stringByExpandingTil)
var homeDir = URL.init(fileURLWithPath: urlS) //URL.appendingPathComponent(URL(string: urlS))
let date: String? = formatter?.string(from: Date())
let file = homeDir.appendingPathComponent("xyz-" + (date!)).appendingPathExtension("m4a")
The Swift equivalent is Swift的等效项是
let formatter : DateFormatter = {
let df = DateFormatter()
df.dateFormat = "YYYYMMDDHHmmss"
return df
}()
let homeDir = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("xyz")
let date = formatter.string(from: Date())
let file = homeDir.appendingPathComponent("xyz-" + date).appendingPathExtension("m4a")
If you want to use the ~
syntax you have to bridge the string to NSString
because expandingTildeInPath
is not available in Swift String
如果你想使用~
语法,你必须弥合字符串NSString
因为expandingTildeInPath
不斯威夫特提供String
let homeDir = URL(fileURLWithPath:("~/xyz/" as NSString).expandingTildeInPath).appendingPathComponent("xyz")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.