I have a url that I want get some json data from, when I load the URL in a webpage this is what the json looks like, how can I get these values in swift?
{
"name" : "name value"
"serial_number" : "serial_numbe value"
"status" : "status value"
...
}
this is what i've so far but it isn't working. I am getting an invalid conversion from throwing function of type... error on my URLSession.shared call
let web = URL(string: "192.168.101.1:8080/api")
let webRequest = URLRequest(url: web!)
URLSession.shared.dataTask(with: webRequest, completionHandler: {(data, response, error) in
guard let data = data, error == nil else {return}
do{
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
let main = json as? [String : Any] ?? []
print(["name"])
}
})
You have syntax errors in there.
guard let web = URL(string: "192.168.101.1:8080/api") else { return }
URLSession.shared.dataTask(with: web) { (data, response, error) in
guard error == nil, let data = data else { return }
do {
let serializedData = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
guard let json = serializedData as? [String : Any] else { return }
print(json["name"])
} catch {
debugPrint(error)
}
}.resume()
You can try
let web = URL(string: "192.168.101.1:8080/api")
let webRequest = URLRequest(url: web!)
URLSession.shared.dataTask(with: webRequest, completionHandler: {(data, response, error) in
guard let data = data, error == nil else {return}
do{
let main = try JSONSerialization.jsonObject(with: data) as! [String:Any]
print(main["name"])
// or
let dec = JSONDecoder()
dec.keyDecodingStrategy =.convertFromSnakeCase
let res = dec.decode(Root.self, from: data)
}
catch {
print(error)
}
}).resume()
struct Root: Codable {
let name, serialNumber, status: String
}
Related
I have the following code to get the path between two points in Google maps iOS SDK. However, I am not receiving any data back or any errors even.
let url = URL(string: "http://maps.googleapis.com/maps/api/directions/json?origin=\(latitude),\(longitude)&destination=\(finallat),\(finallong)&key=**************")
URLSession.shared.dataTask(with: url!) { (data:Data?, response:URLResponse?, error:Error?) in
if let data = data {
do {
// Convert the data to JSON
let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
if let json = jsonSerialized, let url = json["url"], let explanation = json["explanation"] {
print(url)
print(explanation)
}
} catch let error as NSError {
print(error.localizedDescription)
}
} else if let error = error {
print(error.localizedDescription)
}
}
You don't do anything with the dataTask so it isn't actually being called. You need to call resume().
let url = URL(string: "http://maps.googleapis.com/maps/api/directions/json?origin=\(latitude),\(longitude)&destination=\(finallat),\(finallong)&key=**************")
let task = URLSession.shared.dataTask(with: url!) { (data:Data?, response:URLResponse?, error:Error?) in
if let data = data {
do {
// Convert the data to JSON
let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
if let json = jsonSerialized, let url = json["url"], let explanation = json["explanation"] {
print(url)
print(explanation)
}
} catch let error as NSError {
print(error.localizedDescription)
}
} else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
This is the Url I am requesting for :
https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq
If you run this on browser, it works fine and gives a JSON response. However I get this error in the catch block on running the following code : URLSession parameters must be valid :
let callURL = URL.init(string: urlString) // urlString is the above url
var request = URLRequest.init(url: callURL!)
request.addValue(ContentType_ApplicationJson, forHTTPHeaderField: HTTPHeaderField_ContentType)
request.httpMethod = HTTPMethod_Get
let dataTask = urlSession.dataTask(with: request) { (data,response,error) in
if error != nil{
completion(nil)
return
}
do {
if let resultJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary{
print("Result",resultJson)
if let news = resultJson.value(forKeyPath: "articles") as? [NSDictionary]{
print("News",news)
completion(news)
return
}
}
} catch {
print("Error -> \(error)")
}
}
dataTask.resume()
I am not sure what is wrong in your code but I have tested your above code in playground I am getting news below is the code
import Foundation
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let urlString = "https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq"
let callURL = URL.init(string: urlString) // urlString is the above url
var request = URLRequest.init(url: callURL!)
request.addValue("Content-Type", forHTTPHeaderField: "application/json")
request.httpMethod = "GET"
let dataTask = URLSession.shared.dataTask(with: request) { (data,response,error) in
let res = response as! HTTPURLResponse
print(res)
if error != nil{
print(error!)
return
}
do {
if let resultJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary{
print("Result",resultJson)
if let news = resultJson.value(forKeyPath: "articles") as? [NSDictionary]{
print("News",news)
return
}
}
} catch {
print("Error -> \(error)")
}
}
dataTask.resume()
This worked with me
let callURL = URL.init(string: "https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq") // urlString is the above url
var request = URLRequest.init(url: callURL!)
request.httpMethod = HTTPMethod.get.rawValue
let dataTask = URLSession.shared.dataTask(with: request) { (data,response,error) in
if error != nil{
print(error)
}
do {
if let resultJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary{
print("Result",resultJson)
if let news = resultJson.value(forKeyPath: "articles") as? [NSDictionary]{
print("News",news)
return
}
}
} catch {
print("Error -> \(error)")
}
}
dataTask.resume()
You don't need an URLRequest for a GET request, it's the default, just pass the URL
This works, however there is no value for key articles
let urlString = "https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq"
let callURL = URL(string: urlString)!
let dataTask = URLSession.shared.dataTask(with: callURL) { (data,response,error) in
if error != nil { return }
do {
if let resultJson = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
print("Result",resultJson)
// if let news = resultJson["articles"] as? [[String:Any]] {
// print("News",news.count)
// return
// }
}
} catch {
print("Error -> \(error)")
}
}
dataTask.resume()
And – as always – do not use NSDictionary and valueForKey in Swift and .allowFragments is pointless if the root object is a collection type.
Iam getting an error while i try to send the POST request in swift 3. Any one please suggest me the correct syntax for URLSession.shared method in swift 3. this is what i tried. iam new here.
let task = URLSession.shared.dataTask(with: request, completionHandler: {
(data, response, error) in
if error != nil{
print("error");
return
}
do{
let myjson = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parsejson = myjson{
var msg: String!
msg = parsejson["message"] as! String?
print(msg)
}catch error {
print ("")
}
}
})
task.resume().
Here's working URLSession.shared code. I don't have your URL so I used one that is online, free, and produces JSON:
let someURL = URL(string:"https://jsonplaceholder.typicode.com/posts/2")!
let request = URLRequest(url: someURL)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print("error")
return
}
guard let data = data else {
print("No data")
return
}
do {
if let myjson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? Dictionary<String,Any> {
if let title = myjson["title"] {
print("Title was \"\(title)\"")
}
}
} catch {
print("Error parsing JSON: \(error)")
}
}
task.resume()
This outputs Title was "qui est esse" for me.
let defaultConfiguration = URLSessionConfiguration.default
let operationQueue = OperationQueue.main
let defaultSession = URLSession(configuration: defaultConfiguration, delegate: self, delegateQueue: operationQueue)
if let url = URL(string: "https://newsapi.org/v1/articles?source=abc-news-au&sortBy=top&apiKey=47d2ce48babd47b1bc391b426b89ca23")
{
(defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil{
return
}
do {
let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
if var dataDictionary = resultJson {
// dataDictionary["access_token"] as AnyObject
self.dataArray = dataDictionary["articles"] as! [Any]
var dataDictionary22 = self.dataArray[0] as! [String: Any] as [String : AnyObject]
let url = URL(string:
"\(String(describing: dataDictionary22["urlToImage"]!))")
print("url -> \(String(describing: url!))")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard let data = data, error == nil else {
return
}
self.imageView.image = UIImage(data: data)
}
task.resume()
}
} catch {
print("Error -> \(error)")
}
}).resume()
}
i am trying to get news updates from open api through nsurlsession and it has dictionary->array->dictionary->at key "urlToImage"
but iam getting url like http://www.abc.net.au/news/image/8968140-1x1-700x700.jpg but not getting image file in data it was empty can any one minimige the code lenth and solve my problem
Using this piece of code, you can parse that specific URL response successfully, I have tested it in a Playground.
This: "\(String(describing: dataDictionary22["urlToImage"]!))" is not the way get a String from an AnyObject, you should use conditional casting.
if let url = URL(string: "https://newsapi.org/v1/articles?source=abc-news-au&sortBy=top&apiKey=47d2ce48babd47b1bc391b426b89ca23"){
URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in
guard error == nil, let data = data else {
print(error!);return
}
guard let resultJson = (try? JSONSerialization.jsonObject(with: data)) as? [String:Any] else {
return
}
print(resultJson)
guard let articles = resultJson["articles"] as? [[String:Any]], let firstArticle = articles.first else { return }
guard let imageUrlString = firstArticle["urlToImage"] as? String, let imageUrl = URL(string: imageUrlString) else { return }
URLSession.shared.dataTask(with: imageUrl, completionHandler: { data, response, error in
guard error == nil, let data = data else {
print(error!);return
}
let image = UIImage(data: data)
DispatchQueue.main.async {
self.imageView.image = image
}
}).resume()
}).resume()
}
If you want to get all article pictures (in your question you were only parsing the first one), just change guard let articles = resultJson["articles"] as? [[String:Any]], let firstArticle = articles.first else { return } to the following:
for article in articles {
guard let imageUrlString = article["urlToImage"] as? String, let imageUrl = URL(string: imageUrlString) else { return }
URLSession.shared.dataTask(with: imageUrl, completionHandler: { data, response, error in
guard error == nil, let data = data else {
print(error!);return
}
let image = UIImage(data: data)
//use the image
}).resume()
}
let url1 = "https://jsonplaceholder.typicode.com/posts"
var request = URLRequest(url: URL(string: url1)!)
request.httpMethod = "GET"
let urlSession = URLSession.shared
let task = urlSession.dataTask(with: request, completionHandler: {(data,response,error) -> Void in
if let error = error {
print(error)
return
}
if let data = data {
OperationQueue.main.addOperation({ () -> Void in
self.tableView.reloadData()
})
}
})
task.resume()
With or without http method, response data is empty. What am I doing wrong? WiFi works fine. Maybe problem on my simulator settings?
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
let posts = json as? [[String: Any]] ?? []
print(posts)
for post in posts{
let product = Product()
product.userId = post["userId"] as! Int
product.id = post["id"] as! Int
product.title = post["title"] as! String
product.body = post["body"] as! String
self.products.append(product)
}
} catch let error as NSError {
print(error)
}
}).resume()
Yeah thanks, but your code is not works too, i mean say data is empty, nothing to be parsed. WiFi on my emulator works fine maybe problem on my xcode8?
Made some changes in your code.
let url = NSURL(string: "https://jsonplaceholder.typicode.com/posts")
NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest.init(URL: url!), completionHandler: {(data, response, error) in
guard let data = data where error == nil else { return }
do {
let posts = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
print(posts)
} catch let error as NSError {
print(error)
}
}).resume()
Output :
Here your all 100 post display