Naishta
Naishta

Reputation: 12353

Cannot convert value of type 'NSString'? to expected argument type 'String'

I am trying to load HTML content from this website onto a Webview. But I am getting the following error:

Cannot convert value of type 'NSString?' to expected argument type 'String'

Here is my code:

override func viewDidLoad() {
        super.viewDidLoad()

        let webUrl = NSURL(string: "http://www.stackoverflow.com/users/5438240/naishta")

        let webContent = NSURLSession.sharedSession().dataTaskWithURL(webUrl!){
            (data,response,error) in

            if error == nil{

                let readableForm = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print(readableForm)

                self.displayWeb.loadHTMLString(readableForm, baseURL: nil) //here is where the error is thrown
            }


        }
        webContent.resume()

    }

Upvotes: 1

Views: 5433

Answers (3)

Albi
Albi

Reputation: 1855

The actual way is

var a:NSString = "this is"
let c = String(a)

Upvotes: -1

Naishta
Naishta

Reputation: 12353

Was able to resolve myself with the change as below, needed a "as! String" conversion

 self.displayWeb.loadHTMLString(readableForm as! String, baseURL: nil)

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236340

You should use Swift native type String and use guard to make sure data it is not nil as follow:

guard 
    let data = data where error == nil, readableForm = String(data: data, encoding: NSUTF8StringEncoding)
else { return }

print(readableForm)
self.displayWeb.loadHTMLString(readableForm, baseURL: nil)

Upvotes: 3

Related Questions