I have a little problem with looping in Swift 3. I have one JSONArray and one JSONObject like below :
dataReqList [Any] :
[{
bezeich = "MORE SALT";
grpnr = 0;
nr = 1;
}, {
bezeich = "MORE SWEET";
grpnr = 0;
nr = 2;
}, {
bezeich = "MORE PEPPER";
grpnr = 0;
nr = 3;
}, {
bezeich = "MORE CHILLI";
grpnr = 0;
nr = 4;
}, {
bezeich = COLD;
grpnr = 0;
nr = 5;
}, {
bezeich = HOT;
grpnr = 0;
nr = 6;
}, {
bezeich = SMALL;
grpnr = 0;
nr = 7;
}, {
bezeich = LARGE;
grpnr = 0;
nr = 8;
}, {
bezeich = "MEDIUM COOKED";
grpnr = 0;
nr = 9;
}, {
bezeich = "WELL DONE";
grpnr = 0;
nr = 10;
}]
currArticle [Anyhashable: Any] :
Optional([AnyHashable("bezeich"): Fresh and Green Salad,
AnyHashable("special-request"): ["MORE PEPPER", "COLD", "HOT"]])
I want to know, how to print the key bezeich in array , if the JSONArray have same String with special-request in JSONObject. I've try this but its not working :
for i in 0..<dataReqList.count {
if ( ((dataReqList[i] as? [AnyHashable: Any])? ["bezeich"] as! String) == (("\(currArticle?["special-request"]!)") as String) ) {
print (dataReqList[i])
}
Any answer and suggest will help for me. Thanks in advance
EDIT :
I'm new in Swift. I have read THIS before but its still not work.
Key special-request with currArticle Dictionary having Array of String as value so you can not directly compare it with string, you can use filter for that like this.
var filterArray = [[String:Any]]()
if let dataArray = dataReqList as? [[String:Any]],
let specialRequestArray = currArticle["special-request"] as? [String] {
filterArray = dataArray.filter { specialRequestArray.contains($0["bezeich"] as? String ?? "") }
print(filterArray)
}
Related
["?xml": {
"#encoding" = "utf-8";
"#version" = "1.0";
}, "root": {
"#id" = 1;
date = "11/25/2018";
message = "";
station = (
{
abbr = 24TH;
etd = (
{
abbreviation = ANTC;
destination = Antioch;
estimate = (
{
bikeflag = 1;
color = YELLOW;
delay = 86;
direction = North;
hexcolor = "#ffff33";
length = 10;
minutes = 4;
platform = 2;
},
{
bikeflag = 1;
color = YELLOW;
delay = 0;
direction = North;
hexcolor = "#ffff33";
length = 10;
minutes = 23;
platform = 2;
},
{
bikeflag = 1;
color = YELLOW;
delay = 0;
direction = North;
hexcolor = "#ffff33";
length = 10;
minutes = 43;
platform = 2;
}
);
limited = 0;
},
{
abbreviation = DALY;
destination = "Daly City";
estimate = (
{
bikeflag = 1;
color = BLUE;
delay = 214;
direction = South;
hexcolor = "#0099cc";
length = 9;
minutes = 11;
platform = 1;
},
{
bikeflag = 1;
color = BLUE;
delay = 0;
direction = South;
hexcolor = "#0099cc";
length = 9;
minutes = 27;
platform = 1;
},
{
bikeflag = 1;
color = BLUE;
delay = 0;
direction = South;
hexcolor = "#0099cc";
length = 9;
minutes = 47;
platform = 1;
}
);
limited = 0;
},
{
abbreviation = DUBL;
destination = "Dublin/Pleasanton";
estimate = (
{
bikeflag = 1;
color = BLUE;
delay = 0;
direction = North;
hexcolor = "#0099cc";
length = 9;
minutes = 10;
platform = 2;
},
{
bikeflag = 1;
color = BLUE;
delay = 0;
direction = North;
hexcolor = "#0099cc";
length = 9;
minutes = 30;
platform = 2;
},
{
bikeflag = 1;
color = BLUE;
delay = 0;
direction = North;
hexcolor = "#0099cc";
length = 9;
minutes = 50;
platform = 2;
}
);
limited = 0;
},
{
abbreviation = MLBR;
destination = "SFO/Millbrae";
estimate = (
{
bikeflag = 1;
color = YELLOW;
delay = 245;
direction = South;
hexcolor = "#ffff33";
length = 10;
minutes = 17;
platform = 1;
},
{
bikeflag = 1;
color = YELLOW;
delay = 254;
direction = South;
hexcolor = "#ffff33";
length = 10;
minutes = 38;
platform = 1;
},
{
bikeflag = 1;
color = YELLOW;
delay = 0;
direction = South;
hexcolor = "#ffff33";
length = 10;
minutes = 53;
platform = 1;
}
);
limited = 0;
}
);
name = "24th St. Mission";
}
);
time = "05:28:01 PM PST";
uri = {
"#cdata-section" = "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=24TH&json=y";
};
}]
Want to get abbr, abbreviation, minutes in three separate arrays. So the root is a separate element as in, key1 = xml and key2 = root.
this is what I have. I am getting till estimates array but not able to get the values like I mentioned before.
static func singleRoute(_ station: String?, completionHandler: #escaping (SingleRouteModel?) -> Void) {
let routeURL = URL(string: "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=\(station ?? "12TH")&key=MW9S-E7SL-26DU-VV8V&json=y")
var routeModel = SingleRouteModel()
URLSession.shared.dataTask(with: routeURL!) { (data, response, error) in
if error == nil {
do {
guard let todo = try JSONSerialization.jsonObject(with: data!, options:.mutableContainers)
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
print("todo = \(todo)")
let root = todo["root"] as? [String: Any]
let station = root?["station"] as? [[String: Any]]
var etd: [[String : Any]]?
var estimate: Any?
for (_, value) in (station?.enumerated())! {
etd = value["etd"] as? [[String: Any]]
}
var estimates: [String: Any]? = [:]
if let etd = etd {
for (key, value) in etd.enumerated() {
estimates?["\(key)"] = value
}
} else {
completionHandler(nil)
}
if let estimate = estimates {
for (k, v) in estimate {
print(v)
}
}
completionHandler(routeModel)
} catch {
print("error trying to convert data to JSON")
return
}
} else {
print("no data")
}
}.resume()
}
Here's the code in Playground form:
import Foundation
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
struct Estimate: Codable {
let minutes: String
}
struct ETD: Codable {
let abbreviation: String
let estimate: [Estimate]
}
struct Station: Codable {
let abbr: String
let etd: [ETD]
}
struct Root: Codable {
let station: [Station]
}
struct SingleRouteModel: Codable {
let root: Root
}
func singleRoute(_ station: String?, completionHandler: #escaping (SingleRouteModel?) -> Void) {
let routeURL = URL(string: "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=\(station ?? "12TH")&key=MW9S-E7SL-26DU-VV8V&json=y")
URLSession.shared.dataTask(with: routeURL!) { (data, response, error) in
if let data = data {
let model = try? JSONDecoder().decode(SingleRouteModel.self, from: data)
completionHandler(model)
}
else {
completionHandler(nil)
}
}.resume()
}
singleRoute(nil, completionHandler: { model in
guard let model = model else { print("failed"); return }
let abbrs = model.root.station
.map { $0.abbr }
let abbreviations = model.root.station
.flatMap { $0.etd }
.flatMap { $0.abbreviation }
let minutes = model.root.station
.flatMap { $0.etd }
.flatMap { $0.estimate }
.map { $0.minutes }
print("abbrs:", abbrs)
print("abbreviations:", abbreviations)
print("minutes:", minutes)
})
I'm trying to send an array of dictionaries as one of the parameters to an Alamofire request. However, Alamofire is failing on the request.
class PromoCategory {
var promoCategoryId : Int?
var activityId : Int?
var promoCategoryName : String?
var activityName : String!
var statusCd : Int?
init() {
promoCategoryId = 0
promoCategoryName = ""
}
func getDictFormat() -> [String: Any] {
if activityId == nil { activityId = 0 }
if statusCd == nil { statusCd = 0 }
return [
"promoCategoryId" : "\(promoCategoryId!)",
"activityId" : "\(activityId!)",
"promoCategoryName" : promoCategoryName!,
"activityName" : activityName!,
"statusCd" : "\(statusCd!)"
]
}
}
var promoCat = [[String: Any]]()
for cat in promoCategories {
let element = cat.getDictFormat()
promoCat.append(element)
}
var params : [String : Any] = [:]
params["person_id"] = kPersonId
params["person_promo_id"] = promo.personPromoId
params["promo_page_id"] = promo.promoPageId
params["seq_no"] = promo.seqNo
params["promo_type"] = promoTypeString
params["page_name"] = promo.pageName
params["image_name"] = promo.imageName
params["start_date"] = promo.startDate
params["end_date"] = promo.endDate
params["website"] = promo.website
...
params["promoCategories"] = promoCat
Alamofire.request(promoUrl!, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.validate()
.responseJSON { response in
switch response.result {
case .success(let data):
self.json = JSON(data)
print(self.json as Any)
DispatchQueue.main.async(execute: { () -> Void in
self.dismiss(animated: true, completion: nil)
HUD.hide()
})
case .failure(let error):
self.logApiError(url: (...)
}
}
The error:
Request failed with error:
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
If I remove the promoCategories parameter, then it works fine. The params object ends up looking like this:
{
address = "";
bgColorBlue = "0.28936631944444";
bgColorGreen = "0.3072916666666701";
bgColorRed = "0.3063227289789799";
city = "";
"contact_name" = "John Smith";
"contact_phone" = 3065554611;
"country_cd" = CA;
"end_date" = "2017-01-26 21:06:08Z";
"facility_name" = "Conexus Arts Centre";
"image_name" = "EV1.20170126210608302479028.jpg";
latitude = 0;
longitude = 0;
"page_name" = "Test Promo";
"person_id" = 1;
"person_promo_id" = 21;
promoCategories = (
{
activityId = 68;
activityName = "Fashion & Beauty";
promoCategoryId = 271;
promoCategoryName = Accessories;
statusCd = 0;
},
{
activityId = 68;
activityName = "Fashion & Beauty";
promoCategoryId = 273;
promoCategoryName = Beauty;
statusCd = 0;
},
{
activityId = 68;
activityName = "Fashion & Beauty";
promoCategoryId = 270;
promoCategoryName = Fashion;
statusCd = 0;
}
);
"promo_page_id" = 0;
"promo_type" = event;
"prov_state_cd" = "";
"seq_no" = 0;
"start_date" = "2017-01-26 21:06:08Z";
website = "";
}
Is this the approach I should be using? Is there something I have missed? Thanks.
So I have successfully declared some variables obtained by JsonDictionary, but keep on getting nil, here's my code when declaring the variables:
var userName : String!
var text : String!
var name : String!
var tweetID : [NSObject : String]!
var tweetIDStr : String!
var userLocation : String!
var UserImgURLStr : String?
var options : NSJSONReadingOptions!
init(jsonDataDictiony : [String : AnyObject])
{
self.text = jsonDataDictiony["text"] as! String
self.tweetIDStr = jsonDataDictiony["id_str"] as! String
//print(jsonDataDictiony)
if let userDictionary = jsonDataDictiony["user"] as? [String : AnyObject]
{
self.userName = userDictionary["screen_name"] as! String
self.userLocation = userDictionary["location"] as! String
self.name = userDictionary["name"] as! String
}
print(self.text)
print(self.userName)
print(self.userLocation)
print(self.tweetIDStr)
print("-")
}
func castStringToDictionary()
{
let jsonData : NSData = tweetIDStr.dataUsingEncoding(NSUTF8StringEncoding)!
self.tweetID = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: options) as! [NSObject : String]
}
and this is the code when trying to call the function (different class):
var selectedTweet : Tweet!
var twitterNetworkController : NetworkController!
var theTweet = [Tweet]()
override func viewDidLoad()
{
super.viewDidLoad()
self.navigationItem.title = selectedTweet.name + "'s tweet"
twitterNetworkController.fetchTweetID(selectedTweet.tweetID!)
//it gets a nil value here ^
{
(results, error) in
if error == nil
{
self.theTweet = results!
self.selectedFeedTableView.reloadData()
}
else
{
print(error)
}
}
}
Here's the console print:
["in_reply_to_user_id": , "possibly_sensitive_appealable": 0, "favorite_count": 0, "possibly_sensitive": 0, "in_reply_to_status_id": , "in_reply_to_user_id_str": , "lang": en, "favorited": 0, "id": 736420019152637952, "text": 🐐 (at Sate Tegal Marem) — url, "coordinates": , "geo": , "user": {
"contributors_enabled" = 0;
"created_at" = "Mon May 21 09:06:46 +0000 2012";
"default_profile" = 0;
"default_profile_image" = 0;
description = "\Uad1c\Ucc2e\Uc744\Ud150\Ub370 \U2b50";
entities = {
description = {
urls = (
);
};
};
"favourites_count" = 11;
"follow_request_sent" = 0;
"followers_count" = 155;
following = 1;
"friends_count" = 134;
"geo_enabled" = 0;
"has_extended_profile" = 0;
id = 586390966;
"id_str" = 586390966;
"is_translation_enabled" = 0;
"is_translator" = 0;
lang = en;
"listed_count" = 0;
location = "";
name = "tania.";
notifications = 0;
"profile_background_color" = B4DEBA;
"profile_background_image_url" = img url;
"profile_background_image_url_https" = img url;
"profile_background_tile" = 0;
"profile_banner_url" = banner url = img url;
"profile_image_url_https" = img url;
"profile_link_color" = 44A681;
"profile_sidebar_border_color" = FFFFFF;
"profile_sidebar_fill_color" = FFFFFF;
"profile_text_color" = 333333;
"profile_use_background_image" = 1;
protected = 0;
"screen_name" = "tania_alice";
"statuses_count" = 2332;
"time_zone" = Jakarta;
url = "";
"utc_offset" = 25200;
verified = 0;
}, "id_str": 736420019152637952, "created_at": Sat May 28 04:53:09 +0000 2016,
I replaced all the urls since it gave error (my reputation is less than 10 and I cannot post urls)
I am abel to get the current and hourly weather data and based on the following criteria:
viewController:
let dailyWeather = weatherForecast.weekly[0]
let hourlyWeather = weatherForecast.hourly[hour + 4]
let weeklyWeather = weatherForecast.weekly
self.hourlySummaryLabel.text = hourlyWeather.hourlySummary
self.tomorrowSummary.text = dailyWeather.summary
forecast.swift:
struct Forecast {
var currentWeather: CurrentWeather?
var weekly: [DailyWeather] = []
var hourly: [HourlyWeather] = []
init(weatherDictionary: [String: AnyObject]){
if let currentWeatherDictionary = weatherDictionary["currently"] as? [String: AnyObject] {
currentWeather = CurrentWeather(weatherDictionary: currentWeatherDictionary)
}
if let weeklyWeatherArray = weatherDictionary["daily"]?["data"] as? [[String: AnyObject]] {
for dailyWeather in weeklyWeatherArray {
let daily = DailyWeather(dailyWeatherDictionary: dailyWeather)
weekly.append(daily)
}
}
if let hourlyWeatherArray = weatherDictionary["hourly"]?["data"] as? [[String:AnyObject]] {
for hourlyWeather in hourlyWeatherArray {
let hour = HourlyWeather(dailyWeatherDictionary: hourlyWeather)
hourly.append(hour)
}
}
}
}
however, i need to get the full day summary from the following json:
units = si;
}, "hourly": {
data = (
{
{
apparentTemperature = "33.61";
cloudCover = 0;
dewPoint = "12.77";
humidity = "0.27";
icon = "clear-day";
ozone = "279.14";
precipIntensity = 0;
precipProbability = 0;
pressure = "1004.85";
summary = Clear;
temperature = "34.66";
time = 1463464800;
windBearing = 4;
windSpeed = "2.48";
}
);
icon = wind;
summary = "Breezy until this evening."; -----> Need This Summary
is there any way to do it?
I am having some troubles with some json data. I'm making a weather app and most of the information I parsed works but the weather
this is the council output for the json data as a whole this is the section im having troubles with
the full output of json
{
base = stations;
clouds = {
all = 90;
};
cod = 200;
coord = {
lat = "39.74";
lon = "-104.98";
};
dt = 1427305893;
id = 5419384;
main = {
humidity = 84;
pressure = 1022;
temp = "274.07";
"temp_max" = "275.35";
"temp_min" = "272.15";
};
name = Denver;
rain = {
1h = "0.25";
};
snow = {
1h = "0.17";
};
sys = {
country = US;
id = 532;
message = "0.07829999999999999";
sunrise = 1427288058;
sunset = 1427332632;
type = 1;
};
visibility = 4023;
weather = (
{
description = "light rain";
icon = 10d;
id = 500;
main = Rain;
},
{
description = snow;
icon = 13d;
id = 601;
main = Snow;
},
{
description = fog;
icon = 50d;
id = 741;
main = Fog;
},
{
description = mist;
icon = 50d;
id = 701;
main = Mist;
}
);
wind = {
deg = 20;
gust = "14.9";
speed = "12.9";
};
}
i also have it print the keys
[base, id, dt, snow, main, coord, sys, wind, weather, visibility, clouds, cod, name, rain]
I tried to save it as an array but when I set the arry[0] to a string it crashes
my code for the function
func populateLabels(weatherData: NSData){
var jsonError: NSError?
let json = NSJSONSerialization.JSONObjectWithData(weatherData, options: nil, error: &jsonError) as NSDictionary
println(json)
if let city = json["name"] as? String {
CityName.text = city
}
println(json.allKeys)
if let coord = json["coord"] as? NSDictionary {
if let longi = coord["lon"] as? Double {
long.text = String(format: "%.2f", longi)
}
if let lati = coord["lat"] as? Double {
lat.text = String(format: "%.2f", lati)
}
}
if let main = json["main"] as? NSDictionary {
if let temper = main["temp"] as? Double {
temp.text = String(format: "%.2f", temper)
}
}
If anyone knows how to get to the description that would be awesome
thanks js
I got it.. thanks for the help blacksquare, larme, chirag90
if let tasks = json["weather"] as? NSArray
{
if let task = tasks[0] as? NSDictionary
{
if let taskName = task["description"] as? NSString
{
println(taskName)
}
}
}