2017-10-18 79 views
0

正確的URL路徑,這是客觀的C代碼爲什麼我沒有得到斯威夫特OSX

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,我沒有得到正確的URL。可有人幫忙嗎?

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

是應用沙盒?如果是,則無法訪問主目錄。 – vadian

+0

你能告訴我如何知道這個?我對OSX很新。當我使用目標c代碼時,我正在獲取路徑..但​​是我想使用swift代碼。 – solArise

+0

好的沒關係我解決了我的問題 – solArise

回答

0

雨燕相當於是

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因爲expandingTildeInPath不可用斯威夫特String

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