-1

I try to create function to get data from URL:

func getStringFromUrl(urlString: String) -> String {
    if let requestURL = URL(string: urlString) {
        let session = URLSession(configuration: URLSessionConfiguration.default)
        let task = session.dataTask(with: requestURL, completionHandler: { (data, response, error) in
            if let data = data {
                do {
                    let str = String(data: data, encoding: String.Encoding.utf8)
                    return str
                }
                catch let error as NSError {
                    print ("error = \(error)")
                }

            }
            else {
               print ("error = \(error)")
            }
        })
        task.resume()
    }
}

But I got this error: unexpected non-void return value in void function

How can I create a separate function to get data from Url?

Kirill
  • 141
  • 2
  • 11

1 Answers1

2

In your code you have:

let str = String(data: data, encoding: String.Encoding.utf8)
return str

Which is inside a closure block which is not defined to return anything. Because the function session.dataTask is an asynchronous task, it won't return straight away. You should use a completion block/closure to get the response when it returns. Also bear in mind that it might not return, so the string needs to be optional. See the code below.

func getStringFromUrl(urlString: String, completion: @escaping (_ str: String?) -> Void) {
    if let requestURL = URL(string: urlString) {
        let session = URLSession(configuration: URLSessionConfiguration.default)
        let task = session.dataTask(with: requestURL, completionHandler: { (data, response, error) in
            if let data = data {
                do {
                    let str = String(data: data, encoding: String.Encoding.utf8)
                    completion(str)
                }
                catch let error as NSError {
                    print ("error = \(error)")
                    completion(nil)
                }

            }
            else {
                print ("error = \(error)")
                completion(nil)
            }
        })
        task.resume()
    }
}

EDIT: Usage

getStringFromUrl(urlString: "http://google.com") { str in 
   if let text = str {
       // you now have string returned
   }
}
Scriptable
  • 19,402
  • 5
  • 56
  • 72
  • I updated the answer, this question has been marked as a duplicate so the duplicate question should also answer tell you this – Scriptable May 10 '17 at 12:19