为什么我没有在swift OSX中获得正确的URL路径

时间:2017-10-18 09:02:25

标签: ios macos swift3

这是目标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 );

当我尝试将此代码转换为SWIFT 3时,我没有获得正确的网址..任何人都可以帮忙吗?

This is the path I get

~/xyz/xyz-201710291142410.m4a -- file:///Users/xyz/Library/Developer/Xcode/DerivedData/xyz-guhahcdeflytfhhdsxtsrucmqqnv/Build/Products/Debug/

但这是我想要的路径

文件:///Users/xyz/xyz/xyz-201710291142410..m4a

我失败的快速语法

formatter = 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")

1 个答案:

答案 0 :(得分:0)

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")

如果您想使用~语法,则必须将字符串桥接到NSString,因为Swift expandingTildeInPath

中没有String
let homeDir = URL(fileURLWithPath:("~/xyz/" as NSString).expandingTildeInPath).appendingPathComponent("xyz")