错误:类型'String'的值没有成员'URLByAppendingPathComponent'

时间:2015-11-18 17:56:16

标签: ios swift

我的错误是: 类型'String'的值没有成员'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

3 个答案:

答案 0 :(得分:7)

它的

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

Swift 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 :(得分:1)

如错误所述,URLByAppendingPathComponent类没有String方法可用,该函数属于NSURL

您需要使用:

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

或者你可以这样做:

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

答案 2 :(得分:0)

Swift 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

Swift 3 Path

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