Reputation: 33
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 :)
Upvotes: 1
Views: 1338
Reputation: 29
Try this working for me with data JSONSerialization
Blockquote
func callApi(){
let session = URLSession.shared
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")
let task = session.dataTask(with: url!) { (serviceData, urlReponse, error) in
guard error == nil else{
print(error!)
return
}
if let response = urlReponse as? HTTPURLResponse {
print("statusCode \(response.statusCode)")
}
if let data = serviceData, let dataString = String(data: data, encoding: .utf8){
print("String Format" + dataString)
}
// Data Parse
let jsonData = try? JSONSerialization.jsonObject(with: serviceData!, options: .mutableContainers)
let result = jsonData as! Dictionary<String, Any>
print("Dictionary Format \(result)")
}
task.resume() }
Upvotes: 1
Reputation: 143
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()
}
Upvotes: 1