本文介绍了无法使用类型为((fileURLWithPath:NSURL)'的参数列表来调用类型为'NSURL'的初始化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我为Swift 2升级了代码,但出现错误:
I upgraded my code for Swift 2, here I got an error:
无法使用类型为(fileURLWithPath: NSURL)
这是代码:
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.
推荐答案
fileURLWithPath
的语法:
public init(fileURLWithPath path: String)
这意味着它仅接受String
作为参数.并且您将NSURL
作为参数传递.
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)
这篇关于无法使用类型为((fileURLWithPath:NSURL)'的参数列表来调用类型为'NSURL'的初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!