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()
Related
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
}
I am trying to load and parse countries names from json file using swift but I can't
This is file's format which I try to read: Countries JSON File
My code to do this task:
func getJsonFromUrl(){
let url = NSURL(string: COUNTRIES_URL)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
if let countries_array = jsonObj!.value(forKey: "name") as? NSArray {
for country in countries_array {
if let countryDict = country as? NSDictionary {
if let name = countryDict.value(forKey: "name") {
self.countries_names.append((name as? String)!)
}
}
}
}
OperationQueue.main.addOperation ({
self.showNames()
})
}
}).resume()
}
But when I run it, it gives me an error in this line: if let countries_array = jsonObj!.value(forKey: "name") as? NSArray {
because of an unexpected nil.
The JSON starts with a bracket ([) therefore the root object is an array
Don't use NSURL, NSArray and NSDictionary and value(forKey in Swift.
And handle possible errors.
func getJsonFromUrl() {
let url = URL(string: COUNTRIES_URL)!
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) -> Void in
if let error = error { print(error); return }
do {
if let countriesArray = try JSONSerialization.jsonObject(with: data!) as? [[String:String]] {
for country in countriesArray {
self.countries_names.append(country["name"]!)
}
}
} catch { print(error) }
OperationQueue.main.addOperation ({
self.showNames()
})
}).resume()
}
Or much more convenient with Decodable
struct Country : Decodable {
let name : String
}
func getJsonFromUrl() {
let url = URL(string: COUNTRIES_URL)!
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) -> Void in
if let error = error { print(error); return }
do {
let countries = try JSONDecoder().decode([Country].self, from: data!)
self.countries_names = countries.map{$0.name}
} catch { print(error) }
OperationQueue.main.addOperation ({
self.showNames()
})
}).resume()
}
It's an array not dictionary you need
if let dat = data {
if let jsonObj = try? JSONSerialization.jsonObject(with: dat, options:[]) as? [[String:String]]{
jsonObj.forEach { print($0["name"]) }
}
or use Codable
let res = try? JSONDecoder().decode([[String:String]].self,from:data)
or with model
struct Root: Codable {
let name : String
}
let res = try? JSONDecoder().decode([Root].self,from:data)
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