Get data from URL as separate function [duplicate] - ios

This question already has answers here:
function with dataTask returning a value
(4 answers)
Closed 5 years ago.
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?

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
}
}

Related

Swift completion handlers - using escaped closure?

Hi i am a beginner studying swift and would like to know what to use when making an api request. What is the modern and professional way?
is it using an escaping closure like so:
func getTrendingMovies(completion: #escaping (Result< [Movie], Error >) -> Void) {
guard let url = URL(string: "\(Constants.baseUrl)/trending/all/day?api_key=\.(Constants.API_KEY)") else {return}
let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _,
error in
guard let data = data, error == nil else {
return
}
do {
let results = try JSONDecoder().decode(TrendingMoviesResponse.self, from:
data)
completion(.success(results.results))
} catch {
completion(.failure(error))
}
}
task.resume()
}
or should i make an api request without escaping closure while using a sort of delegate like so:
func performRequest(with urlString: String){
if let url = URL(string: urlString){
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { data, response, error in
if error != nil {
delegate?.didFailWithError(error: error!)
return
}
if let safeData = data{
// created parseJson func
if let weather = parseJSON(safeData){
delegate?.didUpdateWeather(self,weather: weather)
}
}
}
task.resume()
} else {
print("url is nil")
}
}
I agree with matt, the modern and professional way is async/await
func getTrendingMovies() async throws -> [Movie] {
let url = URL(string: "\(Constants.baseUrl)/trending/all/day?api_key=\(Constants.API_KEY)")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(TrendingMoviesResponse.self, from: data).results
}

dataTask of URLSession not running

I'm trying to get results from an API, and I'm having trouble running the request itself.
Here is the code I currently have:
let url = URL(string: "https://httpbin.org/get")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("error: \(error)")
} else {
if let response = response as? HTTPURLResponse {
print("statusCode: \(response.statusCode)")
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("data: \(dataString)")
}
}
}
task.resume()
However, it doesn't seem to run anything inside the code block in dataTask.
Thanks for your help :)
Your code works well. It seems like you're just calling the function incorrectly...try it this way:
1:
func request() {
let url = URL(string: "https://httpbin.org/get")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("error: \(error)")
} else {
if let response = response as? HTTPURLResponse {
print("statusCode: \(response.statusCode)")
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("data: \(dataString)")
}
}
}
task.resume()
}
2:
override func viewDidLoad() {
super.viewDidLoad()
request()
}

Store JSON data as a variable

I'm trying to figure out how to store JSON data into a variable for later use. How do I store it, and is it possible to use the variable in another view controller, or do I have to do another request to fetch the data?
This is my code:
#IBAction func signinTapped(_ sender: UIButton) {
guard let url = URL(string: "http://XXXXXX/TestReqIOS.php") else {
return
}
let email = txtEmail.text!
let password = txtPassword.text!
let data : Data = "loginSubmit=1&email=\(email)&password=\(password)&grant_type=password".data(using: .utf8)!
var request : URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
request.setValue(NSLocalizedString("lang", comment: ""), forHTTPHeaderField:"Accept-Language");
request.httpBody = data
print("Calling API")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// vs let session = URLSession.shared
// make the request
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error {
print("error")
}
else if let response = response {
print("response")
}
else if let data = data {
print(data)
}
DispatchQueue.main.async { // Correct
guard let responseData = data else {
print("Error: did not receive data")
return
}
print(String(data: responseData, encoding: String.Encoding.utf8) ?? "")
}
})
task.resume()
}
Which will return:
{
"id": "7",
"first_name": "John",
"last_name": "Doe",
"email": "JohnDoe#text.com",
"created": "2019-03-11",
"modified": "2019-03-10",
}
It would be better to use a struct, such as in your case:
struct Data: Codable {
let id: Int
let first_name: String
let last_name: String
let email: String
let created: Date
let modified: Date
}
Then you create a variable of that struct where you will store it:
var dataVariable = [Data]()
Then you can do your URL call like:
func getData(arr: Bool, completion: #escaping (Bool) -> ()) {
let urlJSON = "URL"
guard let url = URL(string: urlJSON) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
do {
let getData = try JSONDecoder().decode([Data].self, from: data)
self.dataVariable = getData
} catch let jsonErr {
print("error serializing json: \(jsonErr)")
}
completion(arr)
}.resume()
}
Then you can access all of this from the dataVariable var. IF you do this in a Manager class you can access it from any ViewController.
To access:
let firstNameString = dataVariable[0].first_name
If there are not multiple trees of the same, then just make sure its:
let getData = try JSONDecoder().decode(Data.self, from: data)
Edit:
In your case put the above here:
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error {
print("error")
}
else if let response = response {
print("response")
}
else if let data = data {
let getData = try JSONDecoder().decode([Data].self, from: data)
self.dataVariable = getData // <- Just decode here
print(data)
}
DispatchQueue.main.async { // Correct
guard let responseData = data else {
print("Error: did not receive data")
return
}
print(String(data: responseData, encoding: String.Encoding.utf8) ?? "")
}
})
task.resume()

Getting a value from web call in Swift [duplicate]

This question already has answers here:
Returning data from async call in Swift function
(13 answers)
Closed 4 years ago.
I am trying to get the returned value from a PHP script in Swift. However, it seems as though I keep getting the error:
Unexpectedly found nil while unwrapping an Optional value
Here is the class:
var value: String!
func run(idNumber: Int) {
let request = NSMutableURLRequest(url: URL(string: "https://mywebsite.com/file.php")!)
request.httpMethod = "POST"
let postString = "a=Hello"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
//answer = error;
}
let answerString = String(data: data!, encoding: String.Encoding.utf8)
self.value = answerString
}
task.resume()
}
func getValue() -> String{
return value
}
The error occurs when calling the getValue() function. However, when I print out the "answerString" as soon as it is created, it prints out successfully!
The functions are called here:
let access = ApiAccess()
access.run(idNumber: 0)
print(access.getValue())
Making a request is an asynchronous task. You need to wait the closure callback to be call before calling getValue.
You can add a closure callback to your run method. That way you will know when the request has finished and you can print the result:
var value: String!
func run(idNumber: Int, #escaping callback: () -> Void) {
let request = NSMutableURLRequest(url: URL(string: "https://mywebsite.com/file.php")!)
request.httpMethod = "POST"
let postString = "a=Hello"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
//answer = error;
}
let answerString = String(data: data!, encoding: String.Encoding.utf8)
self.value = answerString
callback()
}
task.resume()
}
func getValue() -> String{
return value
}
let access = ApiAccess()
access.run(idNumber: 0) {
print(access.getValue())
}
The issue is that the callback for URLSession.shared.dataTask() happens asynchronously, so you'll end up executing access.getValue() before your var value is ever set. This means that value is forcefully unwrapped before it has a value, which causes this error.
To workaround this, consider using promises, RxSwift, or similar async tools so that you only access values when available.
Refactor your run(idNumber:) function to take a completion handler:
func run(idNumber: Int, completion: (String?, Error?)-> Void ) {
let request = NSMutableURLRequest(url: URL(string: "https://mywebsite.com/file.php")!)
request.httpMethod = "POST"
let postString = "a=Hello"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
completion(nil, error)
}
let answerString = String(data: data!, encoding: String.Encoding.utf8)
self.value = answerString
completion(answerString, nil)
}
task.resume()
}
And call it like this:
let access = ApiAccess()
access.run(idNumber: 0) { result, error in
guard let result = result else {
print("No result. Error = \(error)")
return
}
print("result = \(result)")
}
(Or use Futures or Promises, as mentioned by #JohnEllmore in his answer)

Missing return in a function expected to return 'NSURLSessionDataTask'

I am following a tutorial on accessing an api and parsing the result. I am following the tutorial word for word but I cannot run the program because of 'Missing return in a function expected to return 'NSURLSessionDataTask'
so I changed the return statement to "return NSURLSessionDataTask" but then got an error saying "Cannot convert return expression of type 'NSURLSessionDataTask.Type" to return type 'NSURLSessionDataTask'
How do i figure out the return type? do I even need a return? because in the tutorial there is not return statement (i tried without return as well).
func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void)
-> NSURLSessionDataTask {
let postEndpoint: String = "http://jsonplaceholder.typicode.com/posts/1"
let urlRequest = NSURLRequest(URL: NSURL(string: postEndpoint)!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
(data, response, error) in
guard let responseData = data else {
print("Error: did not recieve data")
return
}
guard error == nil else {
print("error calling GET on /posts/1")
print(error)
return
}
// parse the resutl as JSON, since that's what the API provieds
let post: NSDictionary
do {
post = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as! NSDictionary
} catch {
print("error trying to convert data to JSON")
return
}
// now we have the post, let's just print it to prove we can access it
print("The post is: " + post.description)
if let postTitle = post["title"] as? String {
print("The title is: " + postTitle)
}
})
// and send it
task.resume()
}
Did you really mean to write your own method called dataTaskWithRequest which looks just like the NSURLSession method of the same name? The problem is that you said you're writing a method that returns a NSURLSessionTask object, but you don't return anything.
I'd think you meant something like the following, renaming your own method to something else, and specifying that it's not returning anything itself, because it's not:
func performRequest() {
let postEndpoint: String = "http://jsonplaceholder.typicode.com/posts/1"
let urlRequest = NSURLRequest(URL: NSURL(string: postEndpoint)!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
(data, response, error) in
guard let responseData = data else {
print("Error: did not recieve data")
return
}
guard error == nil else {
print("error calling GET on /posts/1")
print(error)
return
}
// parse the resutl as JSON, since that's what the API provieds
let post: NSDictionary
do {
post = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as! NSDictionary
} catch {
print("error trying to convert data to JSON")
return
}
// now we have the post, let's just print it to prove we can access it
print("The post is: " + post.description)
if let postTitle = post["title"] as? String {
print("The title is: " + postTitle)
}
})
// and send it
task.resume()
}

Resources