am posting to server some data as json and getting json response from it .. like this:
let decoded4 = userDefaults.object(forKey: "nationalities") as! Data
let decodedNationalities = NSKeyedUnarchiver.unarchiveObject(with: decoded4) as! [Nationality]
for nationality in decodedNationalities {
if nationality.name == self.nationality {
idnationality = nationality.id
}
}
if conttype == "Single visit"{
conttype = "single_visit"
}else {
conttype = "multi_visit"
}
print(days)
if days.hasPrefix(","){
days.remove(at: days.startIndex)
}
if days.hasSuffix(","){
days.remove(at: days.endIndex)
}
let todosEndpoint: String = "my link"
guard let todosURL = URL(string: todosEndpoint) else {
print("Error: cannot create URL")
return
}
var todosUrlRequest = URLRequest(url: todosURL)
todosUrlRequest.httpMethod = "POST"
todosUrlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
let newTodo: [String: Any] = ["email": UserDefaults.standard.string(forKey: "CustomerEmail")!, "password": UserDefaults.standard.string(forKey: "CustomerPassword")!, "id_address": addid, "quantity_staff": maidn, "id_service": idservice, "id_region": idregion, "id_city": idcity, "id_nationality": idnationality, "start_date": "2018-05-09", "contract_type": "single_visit", "shift_type": "day", "weekdays": days, "starttime": starttime, "endtime": endtime]
print(newTodo)
let jsonTodo: Data
do {
jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
todosUrlRequest.httpBody = jsonTodo
} catch {
print("Error: cannot create JSON from todo")
return
}
let session = URLSession.shared
let task = session.dataTask(with: todosUrlRequest) {
(data, response, error) in
guard error == nil else {
print("error calling POST on /public/api/register_customer")
print(error!)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let receivedTodo = try JSONSerialization.jsonObject(with: responseData,options: []) as? [String: Any] else {
print("Could not get JSON from responseData as dictionary")
return
}
print("The todo is: " + receivedTodo.description)
guard let status = receivedTodo["success"] as? Int else {
print("Could not get status from JSON")
return
}
if status == 0{
DispatchQueue.main.async {
self.performSegue(withIdentifier: "segueerr", sender: self)
}
print("The status is: 0")
guard let messages = receivedTodo["message"] as? String else {
print("Could not get messages from JSON")
return
}
print(messages)
}
else {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "successsegue", sender: self)
}
print("Success!")
}
} catch {
print(error)
return
}
}
task.resume()
}
when i run it .. it posted the correct values which are:
["email": "lamatat#gmail.com", "id_service": 3, "id_region": 1,
"id_city": 3, "id_address": 22, "weekdays": "tue", "contract_type":
"single_visit", "id_nationality": 4, "password":
"4169faf51ce3c5fb8850451b441a363906f16d69", "endtime": 12,
"starttime": 8, "shift_type": "day", "quantity_staff": 1,
"start_date": "2018-05-09"]
i got error as response which is:
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
when am sure 100% of the values and tried the excat same one in postman and got this as result:
{
"success": true,
"message": "Adding new Order was successful.",
"id_order": 210,
"shift": {
"id": 31,
"id_region": 1,
"id_city": 3,
"id_nationality": 4,
"id_service": 3,
"shift_date": "2018-05-09 00:00:00",
"shift_type": "day",
"weekday": "tue",
"quantity_staff": 64,
"lead_hours": 10,
"created_at": "2018-05-07 12:54:48",
"updated_at": "2018-05-09 10:47:37",
"deleted_at": null,
"price_per_visit": 50
}
}
why would i got this error from the app?!
someone please help! i have no clue whats wrong!
Just try this instead for your one. Change this to
jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
to
let jsonTodo = JSONStringify(value: newTodo as AnyObject)
Add This method inside your controller
func JSONStringify(value: AnyObject,prettyPrinted:Bool = false) -> String{
let options = prettyPrinted ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions(rawValue: 0)
if JSONSerialization.isValidJSONObject(value) {
do{
let data = try JSONSerialization.data(withJSONObject: value, options: options)
if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
return string as String
}
}catch {
print("error")
//Access error here
}
}
return ""
}
*But if you still facing same issue. Change your httoBody also like this
request.httpBody = jsonTodo.data(using: String.Encoding.utf8)
Related
Here is my Response and I want to print the response using array I want to take some details in the response like "Id" and "available" and "leaves" and I have to show in a label in my VC
{
"id": 1,
"emp_id": "001",
"termination_date": "active",
"blood_group": "A+",
"rating": 0,
"noOfStars": 0,
"starOfMonth": false,
"gender": "Female",
"expertise": "",
"experience": "",
"leaves": 0,
"available": 5,
"compoff": 0,
"earnedLeaves": null,
"wfh": 0
}
my code is
struct jsonstruct8:Decodable {
var available: String
var leaves: String
}
var arrdata = [jsonstruct8]()
func getdata(){
let url = URL(string: "MY URL")
URLSession.shared.dataTask(with: url!) { (data, response, error )in
do{if error == nil{
self.arrdata = try JSONDecoder().decode([jsonstruct8].self, from: data!)
for mainarr in self.arrdata{
print(mainarr.available,":",mainarr.leaves)
print(data)
}
}
}catch{
print("Error in get json data")
}
}.resume()
}
I am getting "Error in get json data"
Sample JSON:
{
"id": 1,
"emp_id": "001",
"termination_date": "active",
"blood_group": "A+",
"rating": 0,
"noOfStars": 0,
"starOfMonth": false,
"gender": "Female",
"expertise": "",
"experience": "",
"leaves": 0,
"available": 5,
"compoff": 0,
"earnedLeaves": null,
"wfh": 0
}
Model:
struct Employee: Codable {
let id: Int
let empId: String
let terminationDate: String
let available: Int
let leaves: Int
//add other properties as well....
}
Parsing:
if let data = data {
if let data = data {
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
var employee = try JSONDecoder().decode(Employee.self, from: data)
print("\(employee.available) : \(employee.leaves)") //here you can modify then employee details...
} catch {
print(error)
}
}
}
Edit:
Always update the UI on main thread.
DispatchQueue.main.async {
self.totalLeaves.text = "\(employee.leaves)"
}
I usually use this code to parse most of JSON responses
Before the code, here the JSON I need to get form it the "workspace"
{
"count": 1,
"next": null,
"previous": null,
"results": [{
"id": 307,
"email": "999#ios.net",
"firstName": "fighter",
"categories": [],
"workspace": 302,
"phone": "25485"
}]
}
here is my code:
func getWorkSpace() {
DispatchQueue.main.async {
let returnAccessToken: String? = UserDefaults.standard.object(forKey: "accessToken") as? String
print("UserDefaults Returned Access Token is: \(returnAccessToken!)")
let access = returnAccessToken!
let headers = [
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"postman-token": "dded3e97-77a5-5632-93b7-dec77d26ba99",
"Authorization": "JWT \(access)"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://v5/workspaces/")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error!)
} else {
if let dataNew = data, let responseString = String(data: dataNew, encoding: .utf8) {
print("--------")
print(responseString)
print("--------")
DispatchQueue.main.async {
do {
let json = try JSON(data: data!, options: .allowFragments)
let answer = json["results"]
let workspace = Int(answer["workspace"].int!)
// let workspace = Int(answer["workspace"].string!)!
// let workspace = answer["workspace"].int!
print("Workspace is: \(workspace)")
} catch {
print("Error saving workspace!")
}
}
}
}
})
dataTask.resume()
}
}
This code usually works for me, but this time it's not. Please don't suggest me to use Codables because I didn't learn them yet.
SwiftyJSON
do {
let json = try JSON(data: data1!)
let answer = json["results"].array
answer?.forEach {
print($0["workspace"].int!)
}
} catch {
print("Error saving workspace!")
}
JSONSerialization
let json = try! JSONSerialization.jsonObject(with:data, options :[]) as! [String:Any]
let results = json["results"] as! [[String:Any]]
results.forEach {
print($0["workspace"] as! Int)
}
Codable
struct Root : Codable {
let results:[Model]
}
struct Model: Codable {
let id: Int
let email, firstName: String
let workspace: Int
let phone: String
}
let res = try! JSONDecoder().decode(Root.self, from:data)
print(res.results)
This is my first project working with JSON, so this question could probably be relevant to others in the same situation.
I'm making a weather app using the DarkSky API. So far, I'm requesting the data from the internet, parsing it and, for testing, printing it in the console. Unfortunately, I just get nil. Here's the relevant code:
-> Functions in my ViewController:
func getWeatherData(latitude: String, longitude: String, time: String) {
let basePath = "https://api.darksky.net/forecast/xxxxxxxxxxxxxxxb170/"
let url = basePath + "\(latitude),\(longitude)"
let request = URLRequest(url: URL(string: url)!)
let task = URLSession.shared.dataTask(with: request) {
(data:Data?, response:URLResponse?, error:Error?)
in
if let data = data {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
let dictionary = json
UserDefaults.standard.set(dictionary, forKey: "lastWeatherUpdate")
}
} catch {
print(error.localizedDescription)
}
}
}
}
func getCurrentWeather() {
getWeatherData(latitude: "37", longitude: "40", time: "40000")
let weather = UserDefaults.standard.dictionary(forKey: "lastWeatherUpdate")
print(weather?["latitude"])
}
Does someone spot my mistake? Here's how DarkSky specifies the structure of the JSON data:
"latitude": 47.20296790272209,
"longitude": -123.41670367098749,
"timezone": "America/Los_Angeles",
"currently": {
"time": 1453402675,
"summary": "Rain",
"icon": "rain",
"nearestStormDistance": 0,
"precipIntensity": 0.1685,
"precipIntensityError": 0.0067,
"precipProbability": 1,
"precipType": "rain",
"temperature": 48.71,
"apparentTemperature": 46.93,
"dewPoint": 47.7,
"humidity": 0.96,
"windSpeed": 4.64,
"windGust": 9.86,
"windBearing": 186,
"visibility": 4.3,
"cloudCover": 0.73,
"pressure": 1009.7,
"ozone": 328.35
Well, apparently that's just the important part of the JSON.
Can anyone spot my mistake?
Does someone spot my mistake?
Actually there are two mistakes:
As mentioned in the comments the task must be resumed
dataTask works asynchronously, it requires a completion handler to be able to print something after the call.
The code uses a simple enum with associated types as return type for convenience reasons.
enum WeatherResult {
case success([String:Any]), failure(Error)
}
func getWeatherData(latitude: String, longitude: String, time: String, completion: #escaping (WeatherResult)->()) {
let basePath = "https://api.darksky.net/forecast/xxxxxxxxxxxxxxxb170/"
let urlString = basePath + "\(latitude),\(longitude)"
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
completion(.success(json))
} else {
completion(.failure(NSError(domain: "myDomain", code: 1, userInfo: [NSLocalizedDescriptionKey : "JSON is not a dictionary"])))
}
} catch {
completion(.failure(error))
}
}
task.resume()
}
func getCurrentWeather() {
getWeatherData(latitude: "37", longitude: "40", time: "40000") { result in
switch result {
case .success(let dictionary):
UserDefaults.standard.set(dictionary, forKey: "lastWeatherUpdate")
print(dictionary["latitude"])
case .failure(let error):
print(error.localizedDescription)
}
}
}
I tried the below code for post and get data from json, in struck in getting data from json
http://beta.json-generator.com/api/json/get/EJoC6gB_z
[
{
"UserRole": "User",
"UserName": "Trinadh Reddy",
"Id": 15,
"Email": "trinadhvidavaluru#gmail.com"
},
{
"UserRole": "User",
"UserName": "fayaz sk",
"Id": 16,
"Email": "fayaz.net717#gmail.com"
},
{
"UserRole": "NewUser",
"UserName": "Gowtham M",
"Id": 17,
"Email": "mgowtham666#gmail.com"
},
{
"UserRole": "User",
"UserName": "fayaz sk",
"Id": 18,
"Email": "fayaz8484#gmail.com"
},
{
"UserRole": "NewUser",
"UserName": null,
"Id": 19,
"Email": null
},
{
"UserRole": "User",
"UserName": null,
"Id": 20,
"Email": null
},
{
"UserRole": "NewUser",
"UserName": "Fayaz Shaik",
"Id": 21,
"Email": "fayaz717#gmail.com"
},
{
"UserRole": "NewUser",
"UserName": "Trinadh Reddy",
"Id": 22,
"Email": "trinadh.engineer#gmail.com"
},
{
"UserRole": "NewUser",
"UserName": "tarun gandham",
"Id": 23,
"Email": "gandham.tarun#gmail.com"
},
{
"UserRole": "NewUser",
"UserName": null,
"Id": 24,
"Email": "admin#gmail.com"
},
{
"UserRole": "NewUser",
"UserName": "John",
"Id": 25,
"Email": "john#gmail.com"
},
{
"UserRole": "NewUser",
"UserName": "venkatesh kakumani",
"Id": 26,
"Email": "veenkys01#gmail.com"
}
]
code:
let givenName = user.profile.name
let email = user.profile.email
let param=["UserName":givenName!,"Email":email!] as Dictionary<String,String>
let request = NSMutableURLRequest(url: NSURL(string:"http://sstarapiservice.azurewebsites.net/api/users/")! as URL)
let session = URLSession.shared
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = try! JSONSerialization.data(withJSONObject: param, options: [])
let task = session.dataTask(with: request as URLRequest) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
print("Response: \(json)")
if var role = json["UserRole"] as AnyObject? as! String?
{
print("assigned Role= \(role)")
if role == "User"{
print("App permissions approved")
let myStoryBoard:UIStoryboard = UIStoryboard(name:"Main",bundle:nil)
let page=myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
let pageNav = UINavigationController(rootViewController:page)
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController=pageNav
self.window?.rootViewController=pageNav
//self.window?.rootViewController = page
}
else{
print("wait for Approval...")
let myStoryBoard:UIStoryboard = UIStoryboard(name:"Main",bundle:nil)
let page=myStoryBoard.instantiateViewController(withIdentifier: "ApprovalUser") as! HomeViewController
let pageNav = UINavigationController(rootViewController:page)
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController=pageNav
self.window?.rootViewController=pageNav
// let myStoryBoard:UIStoryboard = UIStoryboard(name:"Main",bundle:nil)
// let page=myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
// let pageNav = UINavigationController(rootViewController:page)
// let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
// appDelegate.window?.rootViewController=pageNav
// self.window?.rootViewController=pageNav
//self.window?.rootViewController = page
}
}
//
}
else {
var jsonStr = " "
var jsonDictionary = [String: Any]()
jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as! String
print("Error could not parse JSON: \(jsonStr)")
print("121")
if var role = jsonStr as String?{
print("role= \(role)")
}
var role = JSONDict["UserRole"] as AnyObject? as! String?
print("success = \(role)")
// if var role = jsonDictionary["UserRole"] as! String?
// {
// print("role is:\(role)")
// }
let myStoryBoard:UIStoryboard = UIStoryboard(name:"Main",bundle:nil)
let page=myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
let pageNav = UINavigationController(rootViewController:page)
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController=pageNav
self.window?.rootViewController=pageNav
}
} catch let parseError {
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Error could not parse JSON: '\(jsonStr)'")
print("12")
}
}
task.resume()
Request JSON data from Webservice APi in Swift 3
Here i have added two types of Methods by Using Alamofire or URLSession : -
import UIKit
import Alamofire
class ViewController: UIViewController {
let urlString = "http://beta.json-generator.com/api/json/get/EJoC6gB_z"
override func viewDidLoad() {
super.viewDidLoad()
// Choose only one function here for calling webservice
getValueofUser()
//Or
getuserDetails()
}
//MARK: - By Using Alamofire
func getValueofUser(){
Alamofire.request(urlString, method: .get)
.responseJSON { response in
print("Success: \(response.result.isSuccess)")
switch response.result {
case .success:
self.successGetTermsData(response: response.result.value! as Any)
case .failure(let error):
print(error)
}
}
}
//MARK: - Or Use URLSession methods
func getuserDetails(){
let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
if error != nil {
print(error ?? "")
} else {
do {
let response = try JSONSerialization.jsonObject(with: data!, options: [])
self.successGetTermsData(response: response)
} catch let error as NSError {
print(error)
}
}
}.resume()
}
func successGetTermsData(response: Any){
let arrayOfDetails = response as? [[String: Any]] ?? []
// Do Something with the Array
//Here you will be get Array of User Related Details
let email = arrayOfDetails[0]["Email"] as? String ?? ""
let username = arrayOfDetails[0]["UserName"] as? String ?? ""
let Id = arrayOfDetails[0]["Id"] as? Int ?? 0
let UserRole = arrayOfDetails[0]["UserRole"] as? String ?? ""
print("Email ID -" ,email, "User Name -", username, "ID -",Id, "UserRole -", UserRole)
}
}
OutPut : -
Email ID - trinadhvidavaluru#gmail.com User Name - Trinadh Reddy ID - 15 UserRole - User
I am working on a weather app that parses JSON data and sets the text of my label to the temp value of the JSON request. I got the value of id from the weather object array, but the temp is not in an array it is just an object. Can someone please tell me where I am wrong. My value is reurning nil because I am not fetching it correctly. Here is my snippet and JSON.
#IBAction func getWeather(sender: AnyObject) {
let requestURL: NSURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=MYAPPID")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("JSON Downloaded Sucessfully.")
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let today = json["weather"] as? [[String: AnyObject]] {
//this is pulling 4 key value pairs
for weather in today {
//this works
let id = weather["id"]?.stringValue
self.trumpDescription.text=id;
print(id)
//this is where I am confused it changes from an array to just an object
let temp = json["temp"] as? String
self.currentTempView.text=temp;
print(temp)
}
}
}
catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}`
Here is the JSON:
{
"coord": {
"lon": 138.93,
"lat": 34.97
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04n"
}
],
"base": "cmc stations",
"main": {
"temp": 292.581,
"pressure": 1019.48,
"humidity": 99,
"temp_min": 292.581,
"temp_max": 292.581,
"sea_level": 1028.92,
"grnd_level": 1019.48
},
"wind": {
"speed": 5.36,
"deg": 237.505
},
"clouds": {
"all": 64
},
"dt": 1464964606,
"sys": {
"message": 0.0037,
"country": "JP",
"sunrise": 1464895855,
"sunset": 1464947666
},
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}
It looks like it should be
if let main = json["main"] as? NSDictionary {
let temp = main["temp"] as! String
print(temp)
}
Instead of this:
let temp = json["temp"] as? String
Try this:
if let main = json["main"] as? [String: AnyObject] {
let temp = main[temp]?.stringValue
print(temp)
//alternatively you can try this as per your convenience of data type
let tempNew = main[temp]?.doubleValue
print(tempNew)
}