I am trying following code to get google maps api response
NSString* apiUrlStr = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%#&sensor=false", saddr, daddr];
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSLog(#"api url: %#", apiUrl);
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSStringEncodingConversionAllowLossy error:Nil];
I got this apiResponse json data from google api:
{
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 23.0236292,
"lng" : 72.60381579999999
},
"southwest" : {
"lat" : 22.990296,
"lng" : 72.5293059
}
},
"copyrights" : "Map data ©2015 Google",
"legs" : [
{
"distance" : {
"text" : "10.8 km",
"value" : 10797
},
"duration" : {
"text" : "23 mins",
"value" : 1403
},
"end_address" : "35, Shivranjani, Jodhpur, Ahmedabad, Gujarat 380015, India",
"end_location" : {
"lat" : 23.0234672,
"lng" : 72.5293059
},
"start_address" : "6, Natvarlal Raval Marg, Archana Society, Bhairavnath, Maninagar, Ahmedabad, Gujarat 380008, India",
"start_location" : {
"lat" : 22.990296,
"lng" : 72.60381579999999
},
"steps" : [
{
"distance" : {
"text" : "0.9 km",
"value" : 898
},
"duration" : {
"text" : "2 mins",
"value" : 123
},
"end_location" : {
"lat" : 22.9943614,
"lng" : 72.5962808
},
"html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eNatvarlal Raval Marg\u003c/b\u003e toward \u003cb\u003eNatvarlal Raval Marg\u003c/b\u003e\u003cdiv style=\"font-size:0.9em\"\u003ePass by Nelsons International School (on the right)\u003c/div\u003e",
"polyline" : {
"points" : "khikC{lczLMBu#jBSd#}AtDg#hA_#z#o#rAYl#O\\yArCgA|BMXQ`#q#bBm#zAcAjCSf#kArCMZ"
},
"start_location" : {
"lat" : 22.990296,
"lng" : 72.60381579999999
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0.2 km",
"value" : 192
},
"duration" : {
"text" : "1 min",
"value" : 40
},
I am using following code to get poly line points
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"points\":\\\"([^\\\"]*)\\\"" options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:apiResponse options:0 range:NSMakeRange(0, [apiResponse length])];
NSString *encodedPoints = [apiResponse substringWithRange:[match rangeAtIndex:1]];
return [self decodePolyLine:[encodedPoints mutableCopy]];
but it returns #"" for encodedPoints
is there any problem in regular expression ?
when you got the response in dictionary then do this,
NSMutableArray *pathArray = [NSMutableArray new];
NSArray *routes = [[directionResponse directionResponse] objectForKey:#"routes"];
NSDictionary *route = [routes lastObject];
DLog(#"Array routes :%#",routes);
if (route) {
NSString *overviewPolyline = [[route objectForKey: #"overview_polyline"] objectForKey:#"points"];
pathArray = [self decodePolyLine:overviewPolyline];
}
NSInteger numberOfSteps = pathArray.count;
CLLocationCoordinate2D coordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++)
{
CLLocation *location = [pathArray objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coordinates[index] = coordinate;
}
MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
I dont think you have to use regex for this, you could use a simple json parser in objetive c and access the poyline and its points, refer :- http://pivotallabs.com/parsing-json-in-objective-c/
Related
So the JSON variable let json = JSON(nearbyChargingSites.jsonString!) contains the current data.:
{
"timestamp" : 1626902257093,
"superchargers" : [
{
"location" : {
"lat" : 63.325319,
"long" : 10.305137
},
"total_stalls" : 19,
"distance_miles" : 10.064082000000001,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 15,
"name" : "Leinstrand, Norway - Klett"
},
{
"location" : {
"lat" : 63.466445999999998,
"long" : 10.91766
},
"total_stalls" : 16,
"distance_miles" : 11.838984999999999,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 16,
"name" : "Stjørdal, Norway"
},
{
"location" : {
"lat" : 63.734355000000001,
"long" : 11.281487
},
"total_stalls" : 12,
"distance_miles" : 31.206503999999999,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 11,
"name" : "Levanger, Norway"
},
{
"location" : {
"lat" : 62.832030000000003,
"long" : 10.009639999999999
},
"total_stalls" : 20,
"distance_miles" : 44.117753,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 17,
"name" : "Berkåk, Norway"
}
],
"congestion_sync_time_utc_secs" : 1626902199,
"destination_charging" : [
{
"distance_miles" : 23.366278999999999,
"name" : "Bårdshaug Herregård",
"location" : {
"lat" : 63.299208,
"long" : 9.8448650000000004
},
"type" : "destination"
},
{
"distance_miles" : 38.390034,
"name" : "Fosen Fjordhotel",
"location" : {
"lat" : 63.959356999999997,
"long" : 10.223908
},
"type" : "destination"
},
{
"distance_miles" : 46.220022999999998,
"name" : "Falksenteret",
"location" : {
"lat" : 63.293301999999997,
"long" : 9.0834460000000004
},
"type" : "destination"
},
{
"distance_miles" : 54.981445000000001,
"name" : "Væktarstua",
"location" : {
"lat" : 62.908683000000003,
"long" : 11.893306000000001
},
"type" : "destination"
}
]
}
I use SwiftyJSON and tries to get the superchargers latitude, longitude and name, like this:
let jsonName = json["superchargers"]["name"]
let jsonLat = json["superchargers"]["location"]["lat"]
let jsonLong = json["superchargers"]["location"]["long"]
When trying to print any of those, all of them return nil.
Any ideas what I am doing wrong, and how to do this?
The reason I want to do this is because I want to add them as annotation to a MKMapView.
The first error is that the JSON initializer you are using will create a single JSON string object, it will not parse the string as JSON data:
Instead of:
let json = JSON(nearbyChargingSites.jsonString!)
you need to use:
let json = JSON(data: dataFromJSONString)
Second you need to iterate over the superchargers array to collect all the values
Try something like:
if let dataFromString = nearbyChargingSites.jsonString!.data(using: .utf8, allowLossyConversion: false) {
let json = try! JSON(data: dataFromString,options: .allowFragments)
for supercharger in json["superchargers"].arrayValue {
let jsonName = supercharger["name"].stringValue
let jsonLat = supercharger["location"]["lat"].doubleValue
let jsonLong = supercharger["location"]["long"].doubleValue
}
}
Please note that the above code does not perform error handling and will crash if values are missing from JSON.
I want to send the city name to the server. I am getting latitude longitude using CLLocationManager. Then I use this link to do reverse geocoding.
https://maps.googleapis.com/maps/api/geocode/json?latlng=lati,longi&key=myApiKey
My problem is for different locations the number of address components are different. As an example, I am getting this array of address componeents for my current location.
"results": [
{
"address_components": [
{
"long_name": "ABC Rd",
"short_name": "ABC Rd",
"types": [
"route"
]
},
{
"long_name": "My City",
"short_name": "My City",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "My Province",
"short_name": "AB",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "My Country",
"short_name": "MC",
"types": [
"country",
"political"
]
}
],
For my client's location im getting this
results": [
{
"address_components": [
{
"long_name": "4",
"short_name": "4",
"types": [
"street_number"
]
},
{
"long_name": "some name",
"short_name": "some name",
"types": [
"route"
]
},
{
"long_name": "some name",
"short_name": "Some name",
"types": [
"political",
"sublocality",
"sublocality_level_2"
]
},
{
"long_name": "some name",
"short_name": "some name",
"types": [
"political",
"sublocality",
"sublocality_level_1"
]
},
{
"long_name": "city",
"short_name": "city",
"types": [
"locality",
"political"
]
},
{
"long_name": "some name",
"short_name": "Some name",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "Client country",
"short_name": "CC",
"types": [
"country",
"political"
]
},
{
"long_name": "12345",
"short_name": "12345",
"types": [
"postal_code"
]
}
],
How can I get the exact city name for different locations when the address components are different. First I tried to get it my component index number but since number of components are different I cant do that. Whats the correct way to do that? Please help me.
Thanks
UPDATE
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks objectAtIndex:0];
NSString *address = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.subLocality,
placemark.subAdministrativeArea,
placemark.country];
// NSString *address=[self.placemark];
NSDictionary *dictAddress = [NSDictionary dictionaryWithDictionary:placemark.addressDictionary];
NSMutableDictionary *dictTxtData = [NSMutableDictionary dictionary];
NSLog(#"----LOCATION NAME----%#",[placemark.addressDictionary valueForKey:#"Name"]);
NSLog(#"-----STREET ADDRESS---%#",[placemark.addressDictionary valueForKey:#"Thoroughfare"]);
NSLog(#"-----CITY-----%#",[placemark.addressDictionary valueForKey:#"City"]);
strCountry=placemark.country;
NSLog(#"Address------%#",address);
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
Results I get
----LOCATION NAME----My Rd
-----STREET ADDRESS---My Rd
-----CITY-----(null)
Address------(null) My Rd
(null) (null)
(null)
My Country
This is how I call to location update
-(void)GetLocationData
{
if (self.locationManager == nil)
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
}
else
{
nil;
}
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
else
{
nil;
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;//kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
}
The json responses from Google API can contain different place marks depending upon the location. Using index is not the correct approach. You can find the city name in json components where type is locality. Below is the code snippet
NSDictionary *locationData = [[json objectForKey:#"results"] objectAtIndex:0];
NSArray* addressComponents= [locationData objectForKey:#"address_components"];
//Iterate each result of address components - find locality and country
NSString *cityName;
for (NSDictionary* address in addressComponents)
{
NSArray* addressType = [address objectForKey:#"types"];
NSString* firstType = [addressType objectAtIndex:0];
if([firstType isEqualToString:#"locality"])
cityName = [address objectForKey:#"long_name"];
}
or you can also use CLGeocoder API in iOS.
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:lat longitude:long];
[ceo reverseGeocodeLocation: loc completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"placemark %#",placemark.locality); // Get the city name
}];
call setLocation() in viewdidload method
func setLocation()
{
// self.view.backgroundColor = UIColor.whiteColor()
self.edgesForExtendedLayout = .None
// Set bounds to inner-west Sydney Australia.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
// print("dofo \(manager.location?.coordinate.latitude)")
// print(manager.location?.coordinate.longitude)
currentlat = (manager.location?.coordinate.latitude)!
cuurentlong = (manager.location?.coordinate.longitude)!
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: currentlat,
longitude: cuurentlong)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
// Address dictionary
print(placeMark.addressDictionary)
// Location name
if let locationName = placeMark.addressDictionary!["Name"] as? NSString {
print(locationName)
}
// Street address
if let street = placeMark.addressDictionary!["Thoroughfare"] as? NSString {
print(street)
}
// City
if let city = placeMark.addressDictionary!["City"] as? NSString {
print(city)
}
// Zip code
if let zip = placeMark.addressDictionary!["ZIP"] as? NSString {
print(zip)
}
// Country
if let country = placeMark.addressDictionary!["Country"] as? NSString {
print(country)
}
})
}
I need to send to a web service this JSON by POST:
{
"plantilla" : "IL3\/il3_prof",
"contacto" : {
"email" : "vgonzalez#ub.edu",
"nombre" : "Vanesa",
"movilPersonal" : "934037680",
"apellidos" : "Gonzalez Jimenez."
"direccionTrabajoDTO" : {
"direccion" : "Feixa Llarga, S\/N 08970 Hospitalet De Llobregat (Barcelona), España"
},
},
"valoresPlantilla" : [
{
"key" : "nombre",
"value" : "Vanesa Gonzalez Jimenez."
},
{
"key" : "curso",
"value" : "Curs de test per Tecnologia"
},
{
"key" : "linked",
"value" : "es.linkedin.com\/in\/"
},
{
"key" : "direccion",
"value" : "Feixa Llarga, S\/N 08970 Hospitalet De Llobregat (Barcelona), España"
},
{
"key" : "email",
"value" : "vgonzalez#ub.edu"
},
{
"key" : "telefono",
"value" : "934037680"
}
]
}
I created the object Tarjeta with values:
Tarjeta *tarjeta = [[Tarjeta alloc] init];
tarjeta.plantilla = #"IL3/il3_prof";
Contacto *contacto = [[Contacto alloc] init];
contacto.nombre = #"Vanesa";
contacto.apellidos = #"Gonzalez Jimenez.";
contacto.email = #"vgonzalez#ub.edu";
contacto.movilPersonal = #"934037680";
DireccionTrabajo *direccionTrabajo = [[DireccionTrabajo alloc] init];
direccionTrabajo.direccion = #"Feixa Llarga, S/N 08970 Hospitalet De Llobregat (Barcelona), España";
contacto.direccionTrabajo = direccionTrabajo;
tarjeta.contacto = contacto;
ValorPlantilla *nombre = [[ValorPlantilla alloc] init];
nombre.key = #"nombre";
nombre.value = #"Vanesa Gonzalez Jimenez.";
ValorPlantilla *curso = [[ValorPlantilla alloc] init];
curso.key = #"curso";
curso.value = #"Curs de test per Tecnologia";
ValorPlantilla *linked = [[ValorPlantilla alloc] init];
linked.key = #"linked";
linked.value = #"es.linkedin.com/in/";
ValorPlantilla *direccion = [[ValorPlantilla alloc] init];
direccion.key = #"direccion";
direccion.value = #"Feixa Llarga, S/N 08970 Hospitalet De Llobregat (Barcelona), España";
ValorPlantilla *email = [[ValorPlantilla alloc] init];
email.key = #"email";
email.value = #"vgonzalez#ub.edu";
ValorPlantilla *telefono = [[ValorPlantilla alloc] init];
telefono.key = #"telefono";
telefono.value = #"934037680";
tarjeta.valoresPlantilla = [NSArray arrayWithObjects:nombre, curso, linked, direccion, email, telefono, nil];
return tarjeta;
After this, I do a conversion from object to JSON with this method:
NSMutableDictionary *tarjetaDict = [[NSMutableDictionary alloc] init];
[tarjetaDict setValue:tarjeta.plantilla forKey:#"plantilla"];
NSMutableDictionary *contactoDict = [[NSMutableDictionary alloc] init];
[contactoDict setValue:tarjeta.contacto.nombre forKey:#"nombre"];
[contactoDict setValue:tarjeta.contacto.apellidos forKey:#"apellidos"];
[contactoDict setValue:tarjeta.contacto.email forKey:#"email"];
[contactoDict setValue:tarjeta.contacto.movilPersonal forKey:#"movilPersonal"];
NSMutableDictionary *direccionDict = [[NSMutableDictionary alloc] init];
[direccionDict setValue:tarjeta.contacto.direccionTrabajo.direccion forKey:#"direccion"];
[contactoDict setValue:direccionDict forKey:#"direccionTrabajoDTO"];
[tarjetaDict setValue:contactoDict forKey:#"contacto"];
[tarjetaDict setValue:tarjeta.valoresPlantilla forKey:#"valoresPlantilla"];
return tarjetaDict;
When I finish this process, I send the NSMutableDictionary like JSON to the web service, but it says that's incorrect and this is the error.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (ValorPlantilla)'
I'm doing anything wrong?
Add this method to your ValorPlantilla class
-(NSMutableDictionary *)getobject
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:self.key forKey:#“key"];
[dict setObject:self.value forKey:#“value"];
return dict;
}
And Change this line
tarjeta.valoresPlantilla = [NSArray arrayWithObjects:[nombre getobject], [curso, linked getobject], [direccion getobject], [email getobject], [telefono getobject], nil];
This might works
First make below six individual dictionary,
{
"key" : "nombre",
"value" : "Vanesa Gonzalez Jimenez."
},
{
"key" : "curso",
"value" : "Curs de test per Tecnologia"
},
{
"key" : "linked",
"value" : "es.linkedin.com\/in\/"
},
{
"key" : "direccion",
"value" : "Feixa Llarga, S\/N 08970 Hospitalet De Llobregat (Barcelona), España"
},
{
"key" : "email",
"value" : "vgonzalez#ub.edu"
},
{
"key" : "telefono",
"value" : "934037680"
}
Then create one array let's say temp array, add this all six dictionary to that array.
Then make below dictionary let's say tempDic,
"contacto" : {
"email" : "vgonzalez#ub.edu",
"nombre" : "Vanesa",
"movilPersonal" : "934037680",
"apellidos" : "Gonzalez Jimenez."
"direccionTrabajoDTO" : {
"direccion" : "Feixa Llarga, S\/N 08970 Hospitalet De Llobregat (Barcelona), España"
},
},
It's having sub dictioanry.
Then make standard dictionary(final) and set three objects : plantilla, tempDic and temp array
So, your object is ready to send.
Now, don't convert it in json. Convert it in NSdata like below
If your final dictionary's name is finalDic then,
NSData *data = [NSJSONSerialization dataWithJSONObject:finalDic options:0 error:nil];
And send that data to server.
If you are using AFNetworking then you not need to convert finalDic to data. Afnetworking manage automatically, just pass that finalDict as parameter of webservice call by AFNetworking.
Hope this will help :)
Please check your json data wrong below url:
http://jsoneditoronline.org/
{
"plantilla" : "IL3\/il3_prof",
"contacto" : {
"email" : "vgonzalez#ub.edu",
"nombre" : "Vanesa",
"movilPersonal" : "934037680",
"apellidos" : "Gonzalez Jimenez.", //Please separate ','
"direccionTrabajoDTO" : {
"direccion" : "Feixa Llarga, S\/N 08970 Hospitalet De Llobregat (Barcelona), España"
} // Please remove separete
},
"valoresPlantilla" : [
{
"key" : "nombre",
"value" : "Vanesa Gonzalez Jimenez."
},
{
"key" : "curso",
"value" : "Curs de test per Tecnologia"
},
{
"key" : "linked",
"value" : "es.linkedin.com\/in\/"
},
{
"key" : "direccion",
"value" : "Feixa Llarga, S\/N 08970 Hospitalet De Llobregat (Barcelona), España"
},
{
"key" : "email",
"value" : "vgonzalez#ub.edu"
},
{
"key" : "telefono",
"value" : "934037680"
}
]
}
I want to retrieve data from a JSON file with SwiftyJSON and Alamofire. This is the JSON data:
json: {
"data" : {
"monitors" : [
{
"lines" : [
{
"towards" : "LEOPOLDAU",
"realtimeSupported" : true,
"departures" : {
"departure" : [
{
"departureTime" : {
"countdown" : 2,
"timePlanned" : "2015-09-09T18:47:03.000+0200",
"timeReal" : "2015-09-09T18:47:03.000+0200"
}
},
{
"departureTime" : {
"countdown" : 6,
"timePlanned" : "2015-09-09T18:51:03.000+0200",
"timeReal" : "2015-09-09T18:51:03.000+0200"
}
}
]
},
"lineId" : 301,
"platform" : "1",
"trafficjam" : false,
"richtungsId" : "1",
"direction" : "H",
"type" : "ptMetro",
"name" : "U1",
"barrierFree" : true
}
],
"attributes" : {
},
"locationStop" : {
"type" : "Feature",
"geometry" : {
"type" : "Point",
"coordinates" : [
16.4330680046932,
48.2430825589716
]
},
"properties" : {
"municipality" : "Wien",
"title" : "Kagran",
"coordName" : "WGS84",
"municipalityId" : 90000,
"type" : "stop",
"gate" : "1",
"name" : "60200627",
"attributes" : {
"rbl" : 4127
}
}
}
}
]
}
,
"message" : {
"value" : "OK",
"serverTime" : "2015-09-09T18:45:08.998+0200",
"messageCode" : 1
}
}
What I want to do now is get the data of lines into an array. I tried several combinations for that, e.g.
let departureArray = jsonData["data"]["monitors"][0]["lines"][0].array
or
let departureArray = jsonData["data"]["monitors"]["lines"].array
but my array is always empty. Does anyone has an idea how to do this properly?
Your expected array departureArray is in fact a dictionary
let departureDictionary = jsonData["data"]["monitors"][0]["lines"][0].dictionary
I have this JSON :
{
"_id" : "class_1",
"schedule" : [
{
"date" : "1-1-2014",
"subjects" : [
{
"time_range" : "08:00-10:00",
"subject" : "Sports"
},
{
"time_range" : "10:00-12:00",
"subject" : "History"
}
]
},
{
"date" : "2-1-2014",
"subjects" : [
{
"time_range" : "08:00-10:00",
"subject" : "Physics"
},
{
"time_range" : "10:00-12:00",
"subject" : "Chemistry"
},
{
"time_range" : "10:00-12:00",
"subject" : "Biology"
}
]
},
{
"date" : "3-1-2014",
"subjects" : [
{
"time_range" : "08:00-10:00",
"subject" : "English"
},
{
"time_range" : "10:00-12:00",
"subject" : "Maths"
}
]
},
{
"date" : "4-1-2014",
"subjects" : [
{
"time_range" : "08:00-10:00",
"subject" : "Spanish"
},
{
"time_range" : "10:00-12:00",
"subject" : "Choreography"
},
{
"time_range" : "12:00-14:00",
"subject" : "Music"
},
{
"time_range" : "14:00-16:00",
"subject" : "Sports"
},
{
"time_range" : "16:30-18:30",
"subject" : "Religion"
}
]
}
]
}
What I would like to do is get an NSArray/NSMutableArray or NSDictionary/NSMutableDictionary` with the subjects for a GIVEN date. So for example if I type in the date 4-1-2014, I would like to get an array or dictionary with the 5 subjects that are contained in that date.
What I would like to do is get an NSArray/NSMutableArray or NSDictionary/NSMutableDictionary with the subjects for a GIVEN date. So for example if I type in the date 1-1-2014, I would like to get an array or dictionary with the 2 subjects that are contained in that date.
This is what I have tried:
//NSDICTIONARY CONTAINING CLASS DATA FOR CLASS ID
NSDictionary *classData =
[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&error];
//NSMUTABLEDICTIONARY CONTAINING SCHEDULE DATA FOR CLASS ID
NSMutableArray *scheduleDatabyClassID = [classData objectForKey:#"schedule"];
//NSMUTABLEARRAY CONTAINING SCHEDULE SUBJECTS OF CLASS ID
NSMutableArray *subjectsDatabyDate =[[NSMutableArray alloc] init] ;
for (NSMutableDictionary *subjectsData in scheduleDatabyClassID ){
NSString *subjectsData_temp = [subjectsData objectForKey:#"subjects"];
NSString *schedule_date = [subjectsData objectForKey:#"date"];
NSString *check = #"25-11-2013";
if ([schedule_date isEqualToString:check]) {
[subjectsDatabyDate addObject:subjectsData_temp];
}
}
Below is what I would like to get, but WITHOUT MANUALLY setting the index to 0. I want subjectsDataByDate : for the value (1-1-2014) for example.
NSLog(#"subjectsDatabyDate \n %# ", [subjectsDatabyDate objectAtIndex:0]);
This did the trick. As I mentioned, I needed a function that returns me an NSArray with containing the GIVEN date:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"date==%#",#"1-1-2014"];
NSArray *result_wanted = [scheduleDatabyClassID filteredArrayUsingPredicate:predicate];
NSLog(#"THE RESULT \n %# ", result_wanted);
If you do this for many different dates, and repeatedly, I would proceed somehow different.
NSDictionary is a class for key-value pairs. Your whole JSON data is actually a dictionary with keys "_id" and "schedule", and "schedule" has an array value. But looking at the data, a dictionary would have been much more appropriate, with for example "1-1-2014" as key and the rest as data. So you could turn the whole array into a dictionary, similar to your own code:
NSMutableDictionary *subjectsDatabyDate =[NSMutableDictionary dictionary] ;
for (NSDictionary *subjectsData in scheduleDatabyClassID )
{
NSString *schedule_date = [subjectsData objectForKey:#"date"];
subjectsDatabyDate [schedule_date] = subjectsData;
}
Now you can access any date very quickly:
NSDictionary* result_wanted = subjectsDatabyDate [#"1-1-2014"];
The difference is that access to an NSDictionary uses a hash table that will go directly to the item that you want, while the "filteredArray" has to iterate through the whole array, every time you look for a date.