Search code examples
iosswiftxcode6-beta6

Error with Swift Code: String.Type does not have a member named 'stringWithContentOfURL'


I have some code that worked properly before the latest update, After updating to the latest version of Xcode I am getting this error

String.Type does not have a member named 'stringWithContentOfURL'

The code is below.

func searchFlickrForString(searchStr:String, completion:(searchString:String!, flickrPhotos:NSMutableArray!, error:NSError!)->()){
   let searchURL:String = FlickrHelper.URLForSearchString(searchStr)
   let queue:dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

    dispatch_async(queue, {

        var error:NSError?

        let searchResultString:String! = String.stringWithContentsOfURL(NSURL.URLWithString(searchURL), encoding: NSUTF8StringEncoding, error: &error)

        if error != nil{
            completion(searchString: searchStr, flickrPhotos: nil, error: error)
        }

Solution

  • Factory methods have pretty much all been replaced by Swift initializers (this happened quite a while ago, if I remember correctly). The ones you want are:

    let searchResultString:String! = String(contentsOfURL: NSURL(string: searchURL)!, encoding: NSUTF8StringEncoding, error: &error)
    

    Note that NSURL(string:) returns an optional NSURL - handle it however you think best.