2015-11-18 107 views
2

我的錯誤是: 值類型的「字符串」沒有成員「URLByAppendingPathComponent」錯誤:類型「字符串」的值沒有任何成員「URLByAppendingPathComponent」

我在這一行錯誤:

let savePath = documentDirectory.URLByAppendingPathComponent("mergeVideo-\(date).mov") 

我全碼:

// 4 - Get path 
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] 
    var dateFormatter = NSDateFormatter() 
    dateFormatter.dateStyle = .LongStyle 
    dateFormatter.timeStyle = .ShortStyle 
    let date = dateFormatter.stringFromDate(NSDate()) 
    let savePath = documentDirectory.URLByAppendingPathComponent("mergeVideo-\(date).mov") 

    let url = NSURL(fileURLWithPath: savePath) 

我跟着這個教程:Here

回答

5

這是

let savePath = (documentDirectory as NSString).stringByAppendingPathComponent("mergeVideo-\(date).mov") 

因爲documentDirectoryString而非NSURL

編輯

我建議使用這個API:

let documentDirectory = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false) 
var dateFormatter = NSDateFormatter() 
dateFormatter.dateStyle = .LongStyle 
dateFormatter.timeStyle = .ShortStyle 
let date = dateFormatter.stringFromDate(NSDate()) 
let saveURL = documentDirectory.URLByAppendingPathComponent("mergeVideo-\(date).mov") // now it's NSURL 

斯威夫特3+

let documentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) 
var dateFormatter = DateFormatter() 
dateFormatter.dateStyle = .long 
dateFormatter.timeStyle = .short 
let date = dateFormatter.string(from: Date()) 
let saveURL = documentDirectory.appendingPathComponent("mergeVideo-\(date).mov") 
+1

是更改後,該行出現錯誤:''stringByAppendingPathComponent'不可用:改爲在NSURL上使用URLByAppendingPathComponent.' – user5513630

+0

我更新了修復問題的答案。無論如何,最好使用URL相關的API(通過NSFileManager獲取URL)。 – vadian

+0

是的,它的工作。謝謝 – user5513630

1

作爲錯誤狀態,存在可用於String類沒有URLByAppendingPathComponent方法,該函數屬於NSURL

您需要使用:

let savePath = (documentDirectory as NSString).stringByAppendingPathComponent("mergeVideo-\(date).mov") 

或者你可以不喜歡它:

let url  = NSURL(fileURLWithPath: documentDirectory) 
let savePath = url.URLByAppendingPathComponent("mergeVideo-\(date).mov") 
+0

你的代碼會因爲我在vadian答案中發表評論而出錯。 – user5513630

+0

感謝您的重播解決方案 – user5513630

+0

@ user5513630:這是由於swift 2.0,我用另一個替代方案更新我的答案。 –

0

斯威夫特3:URL appendingPathComponent

let documentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) 
     let completeMovie = documentDirectory.appendingPathComponent("movie.mov") // now it's NSURL 

斯威夫特3路徑

let fm = FileManager.default 

     let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) 
     let completeMovie = String(describing: docsurl.appendingPathComponent("merge.mp4")) 
相關問題