How to get the multiple data inside the json curly braces? Swift - json

How to get the multiple data inside the json curly braces in swift3?
Can i use this code to get multiple data? (get "crew_id","crew_name","crew_email")
if let crew = user!["crew"] as? [String:Any], let crewName = crew["crew_name"] as? String {
print(crewName)
JSON
crew ={
"crew_avatar" = "http://ec2-52-221-231-3.ap-southeast-1.compute.amazonaws.com/gv/images/profile_image/Pang_Kang_Ming_916210_0e9.jpg";
"crew_contact" = 0123456789;
"crew_email" = "pang#xover.com.my";
"crew_gender" = Male;
"crew_id" = PP000001;
"crew_name" = "Pang Kang Ming";
"crew_preferred_name" = PKM;
"crew_qrcode" = "images/qrcode/qrcode_085960293a5378a64bec6ebfa3c89bb7.png";
};
message = "Login Sucessfully";
result = success;

Yes you can, just add the values you want to unwrap as below, just be aware that if one of the optional binding does not unwrap, even if others unwrap if statement will not be executed, consider separating the if statements.
Depends on all being returned in the json.
if let crew = user!["crew"] as? [String:Any],
let crewName = crew["crew_name"] as? String,
let crewId = crew["crew_id"] as? String {
print(crewName)
print(crewId)
}
Recommended way, even if some values are not present in the json response, you will be able to get the other values.
if let crew = user!["crew"] as? [String:Any] {
if let crewName = crew["crew_name"] as? String {
print(crewName)
}
if let crewId = crew["crew_id"] as? String {
print(crewId)
}
}

if let file = Bundle.main.url(forResource: "yourJsonFileName", withExtension: "json") {
let data = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: data, options: [])
let jsonData = json as! [[String:Any]]
DispatchQueue.main.async {
let projectName = jsonData.flatMap { $0["crew_avatar"] as? String }
self.crewAvatarArray = projectName
print(self.crewAvatarArray)
let subTitle = jsonData.flatMap { $0["crew_contact"] as? String }
self.crewContactArray = subTitle
let startDate = jsonData.flatMap { $0["crew_email"] as? String }
self.crewEmailArray = startDate
}
}
Try this code

Related

How can I restore my old task with a new one in swift?

I have question about tasks. I need to restore my request, I change link and fetch some new data to that link and show them on my table view. User can change link according to picker view, I have a variable for it and I replaced in link and thats working correct too but in second request can make a thread I assume it is very bad question but I am new in swift. How can I make second or more request in one function.
Here my function code :
func fetchArticles(){
let urlRequest = URLRequest(url: URL(string: "my_api_link_is_here")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (Data,URLResponse,Error) in
if Error != nil {
print(Error!)
}
self.articles = [Article]()
do{
let json = try JSONSerialization.jsonObject(with: Data!, options: .mutableContainers) as! [String: AnyObject]
if let articlesFromJson = json["articles"] as? [[String:AnyObject]] {
for articleFromJson in articlesFromJson {
let article = Article()
let source = articleFromJson["source"] as![String: AnyObject]
let name = source["name"]
if let title = articleFromJson["title"] as? String, let author = name as? String , let desc = articleFromJson["description"] as? String, let url = articleFromJson["url"] as? String, let imageToUrl = articleFromJson["urlToImage"] as? String {
article.author = author as String
if articleFromJson.index(forKey: "description") != nil {
article.desc = desc as String
}else{
article.desc = "empty"
}
article.headline = title as String
article.imageUrl = imageToUrl as String
article.url = url as String
}
self.articles?.append(article)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch let Error {
print(Error)
}
}
task.resume()
}

Accessing Object Attributes from JSON, Swift3

let url = URL(string: "http://192.168.30.243:5000/trippy/destination/info?id=4864cc0a-8")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print ("ERROR")
}
else {
if let content = data {
do {
//Array
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJson)
if let information = myJson as? NSDictionary {
print (information.value(forKey: "EmergencyNumbers")!)
if let number = information.value(forKey: "EmergencyNumbers") as? NSArray {
//This is the part I am unsure about
if let description = number[0] as? AnyObject {
//I know do not know how to access the object's attribute values
}
}
}
}
catch {
}
}
}
}
task.resume()
}
I have used JSON to parse data from the web. I have utilized a dictionary to access the information and then an array to get the data from the certain key. Within this array are lie some objects. How do I access each of these objects' properties' values?
JSON Example:
{
Currency = testCurrency;
DestinationId = "4864cc0a-8";
DialCode = testDialCode;
DoesntUseMetricSystem = 0;
DrinkingAge = 16;
DriverLicense = 1;
EmergencyNumbers = (
{
Description = "Emergency Pizza Delivery";
Id = 1;
Number = 6969;
}
);
Id = 1;
IsNorthHemisphere = 1;
OfficialLanguage = {
Id = 1;
Name = testLanguage;
};
PowerGridVoltage = 226;
PowerSocket = dk;
Telecoms = nonern;
Tipping = 2;
WidelySpokenLanguages = (
{
Id = 2;
Name = testtLanguage;
}
);
WrongSideOfRoad = 0;
}
I see you are coming from Objective-C world, so first I'd recommend you give up using NSArray, NSDictionary etc. in favor of their Swift counterparts Array and Dictionary:
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
...
let JSON = try? JSONSerialization.jsonObject(with: data!, options: [])
if let dictionary = JSON as? [String: Any],
let emergencyNumbers = dictionary["EmergencyNumbers"] as? [[String: Any]]
{
emergencyNumbers.forEach { numbers in
print(numbers["Description"] as? String)
print(numbers["Id"] as? Int)
print(numbers["Number"] as? Int)
}
}
}
By the way [String: Any] is just a syntactic sugar for Dictionary<String, Any>. Same applies to arrays as well: [[String: Any]] is for Array<Dictionary<String, Any>>.
As always, don't use NSArray / NSDictionary in Swift. You throw away the type information.
The root object is a dictionary ([String:Any]), the value for key EmergencyNumbers is an array ([[String:Any]]). Use a loop to iterate thru the array.
if let root = try JSONSerialization.jsonObject(with: content) as? [String:Any] {
print(myJson)
if let emergencyNumbers = root["EmergencyNumbers"] as? [[String:Any]] {
for emergencyNumber in emergencyNumbers {
let description = emergencyNumber["Description"] as? String
let id = emergencyNumber["Id"] as? Int
let number = emergencyNumber["Number"] as? Int
print("description", description ?? "n/a")
print("id", id ?? "n/a")
print("number", number ?? "n/a")
}
}
Some other bad habits:
.mutableContainers is completely meaningless in Swift. The hilarious thing is, everybody who passes the option .mutableContainers assigns the result to an immutable constant.
The unspecified JSON type in Swift 3+ is Any not AnyObject
valueForKey, a KVC method, is inappropriate for this purpose, use objectForKey or key subscription. With Swift native types don't use it at all.

Swift - How To Error Check JSON File?

How would I be able to check whether or not the downloaded JSON content contains an error message rather than the expected content? I've tried to validate the URL but that cannot work due to how a false subdomain (location in this case) still returns an Error Message through the JSON content. I'd appreciate it if anybody could help me out. (Note: I want to check for an invalid location entered by the user and I'm using OpenWeatherMap API.)
func downloadData(completed: #escaping ()-> ()) {
print(url)
//UIApplication.shared.openURL(url as URL)
Alamofire.request(url).responseJSON(completionHandler: {
response in
let result = response.result
if let dict = result.value as? JSONStandard, let main = dict["main"] as? JSONStandard, let temp = main["temp"] as? Double, let weatherArray = dict["weather"] as? [JSONStandard], let weather = weatherArray[0]["main"] as? String, let name = dict["name"] as? String, let sys = dict["sys"] as? JSONStandard, let country = sys["country"] as? String, let dt = dict["dt"] as? Double {
self._temp = String(format: "%.0f °F", (1.8*(temp-273))+32)
self._weather = weather
self._location = "\(name), \(country)"
self._date = dt
}
completed()
})
}
Assuming the resulting JSON has different content when there is an error, check dict for the error content. Below is an example assuming there is a key named error. Adjust as needed based on what you really get when there is an error.
Alamofire.request(url).responseJSON(completionHandler: {
response in
let result = response.result
if let dict = result.value as? JSONStandard {
if let error = dict["error"] {
// parse the error details from the JSON and do what you want
} else if let main = dict["main"] as? JSONStandard, let temp = main["temp"] as? Double, let weatherArray = dict["weather"] as? [JSONStandard], let weather = weatherArray[0]["main"] as? String, let name = dict["name"] as? String, let sys = dict["sys"] as? JSONStandard, let country = sys["country"] as? String, let dt = dict["dt"] as? Double {
self._temp = String(format: "%.0f °F", (1.8*(temp-273))+32)
self._weather = weather
self._location = "\(name), \(country)"
self._date = dt
} else {
// Unexpected content, handle as needed
}
}
completed()
})
You should also provide a parameter to your downloadData completion handler so you can pass back an indication of success or failure so the caller can handle the result appropriately.

Swift : football-data API doesn't work

I'm trying to use football-data.org api. I wrote some code same with before I did sample. But this api is using token and I didn't figured out how to add and do that.
I did these code and nothing happens :
func getData(){
let url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/fixtures"))
url.addValue("my token is here", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
let task = NSURLSession.sharedSession().dataTaskWithRequest(url) { (data, response, error) in
self.setLabels(data!)
}
task.resume()
}
func setLabels(MatchData: NSData){
//var jsonError: NSError?
do{
let json = try NSJSONSerialization.JSONObjectWithData(MatchData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if let sys = json["soccerseason"] as? NSDictionary{
if (sys["href"] as? String) != nil{
let seasonsUrl = sys["href"] as! String
print(seasonsUrl)
}
}
}
catch{
//error
}
}
I'm not getting value or something. I'm new with json. What's wrong in my code?
"soccerseason" is in "_links", like this:
if let links = json["_links"] as? [String:AnyObject],
sys = links["soccerseason"] as? [String:String],
seasonsUrl = sys["href"] {
print(seasonsUrl)
}
This is for the main one.
I've also noticed there's one (the same one, actually) in each dictionary in the main array:
if let fixtures = json["fixtures"] as? [[String:AnyObject]] {
for fixture in fixtures {
if let links = fixture["_links"] as? [String:AnyObject],
sys = links["soccerseason"] as? [String:String],
seasonsUrl = sys["href"] {
print(seasonsUrl)
}
}
}
The URLs are in the _links part in each dictionary in the fixtures array:
if let fixtures = json["fixtures"] as? [[String:AnyObject]] {
for fixture in fixtures {
if let links = fixture["_links"] as? [String:[String:String]],
season = links["soccerseason"],
seasonsUrl = season["href"],
awayTeam = links["awayTeam"],
awayTeamUrl = awayTeam["href"] {
print(seasonsUrl)
print(awayTeamUrl)
}
}
}
And awayTeamName and homeTeamName are at the same level than _links inside the array of dictionaries:
if let fixtures = json["fixtures"] as? [[String:AnyObject]] {
for fixture in fixtures {
if let awayTeamName = fixture["awayTeamName"] as? String,
homeTeamName = fixture["homeTeamName"] as? String {
print(awayTeamName)
print(homeTeamName)
}
}
}

Grab data from JSON file doesn't work

I try to grab data from JSON (http://www.openligadb.de/api/getmatchdata/bl1/2014/15). I want to get every single game with the goals, location, team ...
I tried this but it won't work.
let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"
//parse url
if let JSONData = NSData(contentsOfURL: NSURL(string: url)!) {
if let json = (try? NSJSONSerialization.JSONObjectWithData(JSONData, options: [])) as? NSDictionary {
//handle json
}
}
It doesn't steps in the 2nd if-statement (if let json = (try?...).
I hope you could help me.
Edit get data of dictionaries:
//Data Team1
if let team1 = object["Team1"] as? NSDictionary {
if let name = team1["TeamName"] as? String {
print("Name Team1: \(name)")
}
if let logo = team1["TeamIconUrl"] as? String {
print("Logo Team1: \(logo)")
}
// Etc.
}
What you need to do is to understand your JSON structure: you have an array first, not a dictionary.
This array has dictionaries, each of them holding an array of dictionaries.
It may sound complex but it's actually simple, you just follow the structure of your JSON and decode the values with the correct type.
In JSON, an array starts with [ and a dictionary starts with { (also, be careful not to confuse this JSON syntax with Swift's arrays and dictionaries one).
Your code could be something like this, for example:
do {
let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"
if let url = NSURL(string: url),
JSONData = NSData(contentsOfURL: url),
jsonArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: []) as? NSArray {
for object in jsonArray {
if let goalsArray = object["Goals"] as? NSArray {
// Each "goal" is a dictionary
for goal in goalsArray {
print(goal)
if let name = goal["GoalGetterName"] as? String {
print("Name: \(name)")
}
if let ID = goal["GoalID"] as? Int {
print("ID: \(ID)")
}
// Etc.
}
}
}
}
} catch {
print(error)
}
UPDATE: you're almost there! But "Team1" is a dictionary, not an array. :)
Here's the solution:
do {
let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"
if let url = NSURL(string: url),
JSONData = NSData(contentsOfURL: url),
jsonArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: []) as? NSArray {
for object in jsonArray {
if let team1 = object["Team1"] as? NSDictionary {
if let name = team1["TeamName"] as? String {
print("Name Team1: \(name)")
}
if let logo = team1["TeamIconUrl"] as? String {
print("Logo Team1: \(logo)")
}
}
}
}
} catch {
print(error)
}