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.
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)
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.