Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL(string:) Cannot call value of non-function type 'String'

I have the follow code but I am getting an error.

if let userImageURL = user.image {
    let url = URL(string: userImageURL)
}

How am I supposed to create url? URL(string:) is supposed to take a String isn't it? And that's what userImageURL is.

EDIT: Here's an example of the code I'm trying to implement. Even in this example, I'm getting the same error for catPictureURL

let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")!

// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)

// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
    // The download has finished.
    if let e = error {
        print("Error downloading cat picture: \(e)")
    } else {
        // No errors found.
        // It would be weird if we didn't have a response, so check for that too.
        if let res = response as? HTTPURLResponse {
            print("Downloaded cat picture with response code \(res.statusCode)")
            if let imageData = data {
                // Finally convert that Data into an image and do what you wish with it.
                let image = UIImage(data: imageData)
                // Do something with your image.
            } else {
                print("Couldn't get image: Image is nil")
            }
        } else {
            print("Couldn't get response code for some reason")
        }
    }
}

downloadPicTask.resume()
like image 930
Tommy K Avatar asked Feb 14 '17 05:02

Tommy K


3 Answers

You need to make object of URL like this

let url = Foundation.URL(string:"your_url_string")
like image 179
Gopal Devra Avatar answered Nov 19 '22 01:11

Gopal Devra


In my case this was a namespace problem.

The variable named URL was mucking with the standard URL Type.

Use Foundation.URL in your code or rename the URL variable.

struct NamespaceTest {

    let exampleURL = "http://example.com/"

    var URL: URL {

        // ERROR: Cannot call value of non-function type 'URL'
        return URL(string: exampleURL)!

        // OK
        return Foundation.URL(string: exampleURL)!
    }

}
like image 36
pkamb Avatar answered Nov 18 '22 23:11

pkamb


Was having the same problem, still couldn't figure it out all the way. Feels like an Xcode 8 bug, because according to apple's website it should work (reference: Apple's URL reference)

anyways, I used a workaround for this:

let imageUrl = NSURL(string: "www.apple.com") as! URL
like image 2
B.Malka Avatar answered Nov 19 '22 00:11

B.Malka