Cannot invoke initializer for type 'NSURL' with an argument list of type '(fileURLWithPath: NSURL)'

空扰寡人 提交于 2020-01-07 06:57:57

问题


I upgraded my code for Swift 2, here I got an error:

Cannot invoke initializer for type NSURL with an argument list of type (fileURLWithPath: NSURL)

Here's the code:

    let dirPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let docsDir = dirPaths[0] 
    let soundFilePath = NSURL(fileURLWithPath: docsDir).URLByAppendingPathComponent("sound.caf")
    let soundFileURL = NSURL(fileURLWithPath: soundFilePath)
    //The error goes here. 

回答1:


Syntax of fileURLWithPath:

public init(fileURLWithPath path: String)

Which means it only accept String as argument. And you are passing NSURL as an argument.

And you can solve it this way:

let dirPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let docsDir = dirPaths[0]
let soundFilePath = (docsDir as NSString).stringByAppendingPathComponent("sound.caf")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath)

And here is extension if you want to use:

extension String {

    func stringByAppendingPathComponent(path: String) -> String {

        return (self as NSString).stringByAppendingPathComponent(path)
    }
}

And you can use it this way:

let soundFilePath = docsDir.stringByAppendingPathComponent("sound.caf")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath)



回答2:


You're trying to create an NSURL from an NSURL object, there is no initializer for that. To create the URL properly just replace

let soundFilePath = NSURL(fileURLWithPath: docsDir).URLByAppendingPathComponent("sound.caf")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath)

with

let soundFileURL = NSURL(fileURLWithPath: docsDir).URLByAppendingPathComponent("sound.caf")


来源:https://stackoverflow.com/questions/32665508/cannot-invoke-initializer-for-type-nsurl-with-an-argument-list-of-type-fileu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!