Cannot call initializer for type "NSURL" with argument list of type "(fileURLWithPath: NSURL)"

I updated my code for Swift 2, here I received an error message:

Cannot call initializer for type NSURLusing type argument list(fileURLWithPath: NSURL)

Here is 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. 
0
source share
2 answers

Syntax fileURLWithPath:

public init(fileURLWithPath path: String)

This means that it takes only Stringas an argument. And you pass NSURLas an argument.

And you can solve it like this:

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 the extension if you want to use:

extension String {

    func stringByAppendingPathComponent(path: String) -> String {

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

And you can use it as follows:

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

NSURL NSURL, . URL-,

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

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

Source: https://habr.com/ru/post/1608117/


All Articles