swift get currencycode from country code - swift2

I find the accepted answer to get currencycode from country code in objective c here - How to get ISOCurrencyCode from a ISOCountryCode in iphone sdk?
Can someone help with the swift code to do the same ?

let components: [String: String] = [NSLocaleCountryCode: "CA"]
let identifier = NSLocale.localeIdentifierFromComponents(components)
let locale = NSLocale(localeIdentifier: identifier)
let currencyCode = locale.objectForKey(NSLocaleCurrencyCode)
print(currencyCode)

public static func convertStringCurrencyToNumber(strCurrency:String, locale:String)->Double {
var formatter = NSNumberFormatter()
formatter.currencyCode = locale
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
if let converted:Double = formatter.numberFromString(strCurrency)?.doubleValue {
return converted
}else{
return 0.0
}
}
Changing formatter.locale to formatter.currencyCode works as expected with the ISO 4127 Country and Currency code "USD".

Use below this return type function to get country_code:-
//MARK:- GET COUNTRY CODE
func getCountryPhonceCode (_ country : String) -> String
{
let x : [String] = ["972", "IL",
"93" , "AF",
"355", "AL",
"213", "DZ",
"1" , "AS",
"376", "AD",
"244", "AO",
"1" , "AI",
"1" , "AG",
"54" , "AR",
"374", "AM",
"297", "AW",
"61" , "AU",
"43" , "AT",
"994", "AZ",
"1" , "BS",
"973", "BH",
"880", "BD",
"1" , "BB",
"375", "BY",
"32" , "BE",
"501", "BZ",
"229", "BJ",
"1" , "BM",
"975", "BT",
"387", "BA",
"267", "BW",
"55" , "BR",
"246", "IO",
"359", "BG",
"226", "BF",
"257", "BI",
"855", "KH",
"237", "CM",
"1" , "CA",
"238", "CV",
"345", "KY",
"236", "CF",
"235", "TD",
"56", "CL",
"86", "CN",
"61", "CX",
"57", "CO",
"269", "KM",
"242", "CG",
"682", "CK",
"506", "CR",
"385", "HR",
"53" , "CU" ,
"537", "CY",
"420", "CZ",
"45" , "DK" ,
"253", "DJ",
"1" , "DM",
"1" , "DO",
"593", "EC",
"20" , "EG" ,
"503", "SV",
"240", "GQ",
"291", "ER",
"372", "EE",
"251", "ET",
"298", "FO",
"679", "FJ",
"358", "FI",
"33" , "FR",
"594", "GF",
"689", "PF",
"241", "GA",
"220", "GM",
"995", "GE",
"49" , "DE",
"233", "GH",
"350", "GI",
"30" , "GR",
"299", "GL",
"1" , "GD",
"590", "GP",
"1" , "GU",
"502", "GT",
"224", "GN",
"245", "GW",
"595", "GY",
"509", "HT",
"504", "HN",
"36" , "HU",
"354", "IS",
"91" , "IN",
"62" , "ID",
"964", "IQ",
"353", "IE",
"972", "IL",
"39" , "IT",
"1" , "JM",
"81", "JP", "962", "JO", "77", "KZ",
"254", "KE", "686", "KI", "965", "KW", "996", "KG",
"371", "LV", "961", "LB", "266", "LS", "231", "LR",
"423", "LI", "370", "LT", "352", "LU", "261", "MG",
"265", "MW", "60", "MY", "960", "MV", "223", "ML",
"356", "MT", "692", "MH", "596", "MQ", "222", "MR",
"230", "MU", "262", "YT", "52","MX", "377", "MC",
"976", "MN", "382", "ME", "1", "MS", "212", "MA",
"95", "MM", "264", "NA", "674", "NR", "977", "NP",
"31", "NL", "599", "AN", "687", "NC", "64", "NZ",
"505", "NI", "227", "NE", "234", "NG", "683", "NU",
"672", "NF", "1", "MP", "47", "NO", "968", "OM",
"92", "PK", "680", "PW", "507", "PA", "675", "PG",
"595", "PY", "51", "PE", "63", "PH", "48", "PL",
"351", "PT", "1", "PR", "974", "QA", "40", "RO",
"250", "RW", "685", "WS", "378", "SM", "966", "SA",
"221", "SN", "381", "RS", "248", "SC", "232", "SL",
"65", "SG", "421", "SK", "386", "SI", "677", "SB",
"27", "ZA", "500", "GS", "34", "ES", "94", "LK",
"249", "SD", "597", "SR", "268", "SZ", "46", "SE",
"41", "CH", "992", "TJ", "66", "TH", "228", "TG",
"690", "TK", "676", "TO", "1", "TT", "216", "TN",
"90", "TR", "993", "TM", "1", "TC", "688", "TV",
"256", "UG", "380", "UA", "971", "AE", "44", "GB",
"1", "US", "598", "UY", "998", "UZ", "678", "VU",
"681", "WF", "967", "YE", "260", "ZM", "263", "ZW",
"591", "BO", "673", "BN", "61", "CC", "243", "CD",
"225", "CI", "500", "FK", "44", "GG", "379", "VA",
"852", "HK", "98", "IR", "44", "IM", "44", "JE",
"850", "KP", "82", "KR", "856", "LA", "218", "LY",
"853", "MO", "389", "MK", "691", "FM", "373", "MD",
"258", "MZ", "970", "PS", "872", "PN", "262", "RE",
"7", "RU", "590", "BL", "290", "SH", "1", "KN",
"1", "LC", "590", "MF", "508", "PM", "1", "VC",
"239", "ST", "252", "SO", "47", "SJ",
"963","SY",
"886",
"TW", "255",
"TZ", "670",
"TL","58",
"VE","84",
"VN",
"284", "VG",
"340", "VI",
"678","VU",
"681","WF",
"685","WS",
"967","YE",
"262","YT",
"27","ZA",
"260","ZM",
"263","ZW"]
var keys = [String]()
var values = [String]()
let whitespace = CharacterSet.decimalDigits
//let range = phrase.rangeOfCharacterFromSet(whitespace)
for i in x {
// range will be nil if no whitespace is found
if (i.rangeOfCharacter(from: whitespace) != nil) {
values.append(i)
}
else {
keys.append(i)
}
}
let countryCodeListDict = NSDictionary(objects: values as [String], forKeys: keys as [String] as [NSCopying])
if let t: AnyObject = (countryCodeListDict as? [String : AnyObject])? [country] {
return countryCodeListDict[country] as! String
} else
{
return ""
}
}

Related

How to make a faceted cell graph in ObservableHQ?

I have the following array of objects:
[{ "userid": 1, "groupid": 66123, "date_joined": "2023-01-01", "d0": "10", "d1": "6", "d2": "0", "d3": "1", "d4": "0", "d5": "0", "d6": "0", "d7": "0", "d8": "0", "d9": "0", "d10": "0", "d11": "0", "d12": "0", "d13": "0", "d14": "0" },
{ "userid": 2, "groupid": 66123, "date_joined": "2023-01-01", "d0": "0", "d1": "0", "d2": "2", "d3": "0", "d4": "0", "d5": "0", "d6": "0", "d7": "0", "d8": "0", "d9": "0", "d10": "0", "d11": "0", "d12": "0", "d13": "0", "d14": "0" },
{ "userid": 3, "groupid": 68100, "date_joined": "2023-01-01", "d0": "0", "d1": "0", "d2": "0", "d3": "0", "d4": "0", "d5": "0", "d6": "0", "d7": "0", "d8": "0", "d9": "0", "d10": "0", "d11": "0", "d12": "0", "d13": "0", "d14": "0" }]
and I want to create a faceted cell graph like the following:
where:
each facet is determined by the "groupid"
each row in the facet is the "userid"
there are 15 blocks on each row, corresponding to the respective "d0" - "d14" columns.
Example:
The first facet would be for groupid "66123", with two rows: userid "1" and userid "2". Each row would have 15 columns, each one corresponding to the respective "d0" - "d14" columns.
This code is from the example notebook:
Plot.plot({
height: 1400,
x: {
axis: null,
padding: 0,
},
y: {
padding: 0,
tickFormat: Plot.formatWeekday("en", "narrow"),
tickSize: 0
},
fy: {
reverse: true
},
facet: {
data: DJI,
y: d => d.Date.getUTCFullYear()
},
color: {
type: "diverging",
scheme: "PiYG"
},
marks: [
Plot.cell(DJI, {
x: d => d3.utcWeek.count(d3.utcYear(d.Date), d.Date),
y: d => d.Date.getUTCDay(),
fill: (d, i) => i > 0 ? (d.Close - DJI[i - 1].Close) / DJI[i - 1].Close : NaN,
title: (d, i) => i > 0 ? ((d.Close - DJI[i - 1].Close) / DJI[i - 1].Close * 100).toFixed(1) : NaN,
inset: 0.5
})
]
})
I'm not sure how to change the x: d => d3.utcWeek.count(d3.utcYear(d.Date), d.Date), with to get the graph that I need.
Any help would be greatly appreciated!
Can I suggest that you share a notebook with what you have tried so far? It will be easier to help you if we see where you're at.

Nifi - Route the JSON based on the Array Name

I am new to Nifi, i hv a requirement where we get multiple JSON inputs with different Header Names. I have to parse the JSON and insert into different tables based on the Header value.
Not sure how to use RouteonContent processor or EvaluateJSON Path processor
Input 1
{
"Location": [
{
"country": "US",
"division": "Central",
"region": "Big South",
"locationID": 1015,
"location_name": "Hattiesburg, MS (XF)",
"location_type": "RETAIL",
"location_sub_type": "COS",
"store_type": "",
"planned_open_date": "",
"planned_close_date": "",
"actual_open_date": "2017-07-26",
"actual_close_date": "",
"new_store_flag": "",
"address1": "2100 Lincoln Road",
"address2": "",
"city": "Hattiesburg",
"state": "MS",
"zip": 39402,
"include_for_planning": "Y"
},
{
"country": "US",
"division": "Central",
"region": "Big South",
"locationID": 1028,
"location_name": "Laurel, MS",
"location_type": "RETAIL",
"location_sub_type": "COS",
"store_type": "",
"planned_open_date": "",
"planned_close_date": "",
"actual_open_date": "",
"actual_close_date": "",
"new_store_flag": "",
"address1": "1225 5th street",
"address2": "",
"city": "Laurel",
"state": "MS",
"zip": 39440,
"include_for_planning": "Y"
}
]
Input 2
{
"Item": [
{
"npi_code": "NEW",
"cifa_category": "XM",
"o9_category": "Accessories"
},
{
"npi_code": "NEW",
"cifa_category": "XM0",
"o9_category": "Accessories"
}
]
Use the website https://jsonpath.com/ to figure out the proper JSON expression. But what you could potentially do is use: if the array contains either $.npi_code then do X and if it contains $. country, then do Y

How to change output of the array hash using the map or group_by in ruby?

I have this array of hash where i have to separate same value object and group it by country base on date.
I try to use group_by but i only manage to get the countries i cannot separate the reported_date
outside of array hash.
notice one of the object is thesame
"reported_date": "2020-04-01"
i want it to be outside of every hash so it only print once.
heres my hash
[
{
"reported_date": "2020-04-01",
"country": "Italy",
"confirmed": 110574,
"deaths": 13155,
"recovered": 16847
},
{
"reported_date": "2020-04-01",
"country": "Spain",
"confirmed": 104118,
"deaths": 9387,
"recovered": 22647
},
{
"reported_date": "2020-04-01",
"country": "US",
"confirmed": 83948,
"deaths": 1941,
"recovered": 0
}
]
and i want to change something like this
{
"reported_date": "2020-04-01",
"countries": [
{
"country": "Italy",
"confirmed": 110574,
"deaths": 13155,
"recovered": 16847
},
{
"country": "Spain",
"confirmed": 104118,
"deaths": 9387,
"recovered": 22647
},
{
"country": "US",
"confirmed": 83948,
"deaths": 1941,
"recovered": 0
}
]
}
[
{
"reported_date": "2020-04-01",
"country": "Italy",
"confirmed": 110574,
"deaths": 13155,
"recovered": 16847
},
{
"reported_date": "2020-04-01",
"country": "Spain",
"confirmed": 104118,
"deaths": 9387,
"recovered": 22647
},
{
"reported_date": "2020-04-01",
"country": "US",
"confirmed": 83948,
"deaths": 1941,
"recovered": 0
}
].group_by { |h| h[:reported_date] }.map do |date, rest|
{
reported_date: date,
countries: rest.map { |h| h.reject! { |k| k == :reported_date } }
}
end
Returns
[
{
:reported_date => "2020-04-01",
:countries => [
{
:country => "Italy",
:confirmed => 110574,
:deaths => 13155,
:recovered => 16847
},
{
:country => "Spain",
:confirmed => 104118,
:deaths => 9387,
:recovered => 22647
},
{
:country => "US",
:confirmed => 83948,
:deaths => 1941,
:recovered => 0
}
]
}
]
Suppose your array were:
arr = [
{ date: "2020-04-01", country: "Italy", confirmed: 110574, deaths: 13155},
{ date: "2020-04-02", country: "Spain", confirmed: 104118, deaths: 9387},
{ date: "2020-04-01", country: "US", confirmed: 83948, deaths: 1941},
{ date: "2020-04-02", country: "Italy", confirmed: 120431, deaths: 13394}
]
Depending on your needs you might find it more convenient to reorganize your data, possibly in one of the following two ways.
#1
keeper_keys = arr.first.keys - [:date, :country]
#=> [:confirmed, :deaths]
h = arr.each_with_object({}) { |g,h| h[g[:date]] =
(h[g[:date]] || {}).merge(g[:country]=>g.slice(*keeper_keys)) }
#=> {"2020-04-01"=>{
# "Italy"=>{:confirmed=>110574, :deaths=>13155},
# "US"=>{:confirmed=>83948, :deaths=>1941}
# },
# "2020-04-02"=>{
# "Spain"=>{:confirmed=>104118, :deaths=>9387},
# "Italy"=>{:confirmed=>120431, :deaths=>13394}
# }
# }
h[g[:date]] || {} returns an empty hash if h has no key g[:date].
This allows us to easily compute, for example:
Deaths by date and country
p = h.transform_values { |g| g.transform_values { |f| f[:deaths] } }
#=> {"2020-04-01"=>{"Italy"=>13155, "US"=>1941},
# "2020-04-02"=>{"Spain"=>9387, "Italy"=>13394}}
Total deaths by date
p.transform_values { |g| g.values.sum }
#=> {"2020-04-01"=>15096, "2020-04-02"=>22781}
#2
keeper_keys = arr.first.keys - [:date, :country]
#=> [:confirmed, :deaths]
h = arr.each_with_object({}) { |g,h| h[g[:country]] =
(h[g[:country]] || {}).merge(g[:date]=>g.slice(*keeper_keys)) }
#=> {"Italy"=>{
# "2020-04-01"=>{:confirmed=>110574, :deaths=>13155},
# "2020-04-02"=>{:confirmed=>120431, :deaths=>13394}
# },
# "Spain"=>{
# "2020-04-02"=>{:confirmed=>104118, :deaths=>9387}
# },
# "US"=>{
# "2020-04-01"=>{:confirmed=>83948, :deaths=>1941}
# }
# }
h[g[:country]] || {} returns an empty hash if h has no key g[:country].
This allows us to easily compute:
Deaths by country and date
p = h.transform_values { |g| g.transform_values { |f| f[:deaths] } }
#=> {"Italy"=>{"2020-04-01"=>13155, "2020-04-02"=>13394},
# "Spain"=>{"2020-04-02"=>9387},
# "US"=>{"2020-04-01"=>1941}}
Notice that this expression is the same as the one used earlier to obtain deaths by date and country.
Total deaths by date
p.transform_values { |g| g.values.sum }
#=> {"Italy"=>26549, "Spain"=>9387, "US"=>1941}
Again, this is the same expression as the one used earlier to compute total deaths by country.
Better yet, use a database!

Ruby json2csv fails

using
C:\RubyLearnToProgram>json2csv convert sample.json
results in following error:
Converting sample.json error: undefined method `keys' for
"PREPARED":String
The sample.json:
{
"preparationState": "PREPARED",
"consumerUsageStorageInstruction": {
"de": "gebruik",
"fr": "gebruik",
"en": "gebruik"
},
"npc": "1234",
"drainedWeight": "320.0GR",
"isBaseUnit": "true",
"packagingMarkedExpirationDateType": "BEST_BEFORE_DATE",
"numberOfServingsPerPackage": "100",
"functionalName": "Babbelaars",
"preparationInstructions": {
"de": "koken",
"fr": "koken",
"en": "koken"
},
"brandName": "Test lets try this one",
"manufacturerGln": "5060263871002",
"packagingRefuseObligationName": "ARA",
"gln": "5060263871002",
"height": "129.0MM",
"percentageOfAlcoholByVolume": "0.0",
"dailyValueIntakeReference": "10 a day keeps the doctor away",
"allergenStatement": {
"de": "Enthalt: Milch (Laktose)",
"fr": "Contient: lait de vache (lactose)",
"en": "Bevat: koemelk (lactose)"
},
"isPackagingMarkedReturnable": "false",
"netContent": "325.0GR",
"regulatedProductName": "Babbelaars",
"itemThumbnail": "/a/16257a91e7c42b64fdc7ad91292dce85/babbelaars.png",
"packages": [
{
"height": "100.0CM",
"containedGtin": "90000000000003",
"gtin": "91000000000002",
"width": "50.0CM",
"netContent": "100.0EA",
"packageUnitIndicator": "CASE",
"depth": "60.0CM",
"containedAmount": "10",
"grossWeight": "109.0KG"
}
],
"isVariableUnit": "false",
"taxRate": "STANDARD",
"width": "67.0MM",
"targetMarket": "528",
"gpc": "10000005",
"nameOfInformationProvider": "LANSA",
"depth": "67.0MM",
"grossWeight": "350.0GR",
"nutrients": [{
"percentageOfDailyValueIntake":"0.1","measurementPrecision":"APPROXIMATELY","quantityContainedServingSize":"1.0","quantityContainedHouseHoldServingSize":"10.0","quantityContainedUnit":"GR","nutrientTypeCode":"CHOAVL-"
},{
"percentageOfDailyValueIntake":"0.2","measurementPrecision":"APPROXIMATELY","quantityContainedServingSize":"2.0","quantityContainedHouseHoldServingSize":"20.0","quantityContainedUnit":"E14","nutrientTypeCode":"ENER-"
},{
"percentageOfDailyValueIntake":"0.3","measurementPrecision":"APPROXIMATELY","quantityContainedServingSize":"3.0","quantityContainedHouseHoldServingSize":"30.0","quantityContainedUnit":"GR","nutrientTypeCode":"FASAT"
},{
"percentageOfDailyValueIntake":"0.4","measurementPrecision":"APPROXIMATELY","quantityContainedServingSize":"4.0","quantityContainedHouseHoldServingSize":"40.0","quantityContainedUnit":"KJO","nutrientTypeCode":"ENER-"
},{
"percentageOfDailyValueIntake":"0.5","measurementPrecision":"APPROXIMATELY","quantityContainedServingSize":"5.0","quantityContainedHouseHoldServingSize":"50.0","quantityContainedUnit":"GR","nutrientTypeCode":"FIBTG"
},{
"percentageOfDailyValueIntake":"0.6","measurementPrecision":"APPROXIMATELY","quantityContainedServingSize":"6.0","quantityContainedHouseHoldServingSize":"60.0","quantityContainedUnit":"GR","nutrientTypeCode":"PRO-"
},{
"percentageOfDailyValueIntake":"0.7","measurementPrecision":"APPROXIMATELY","quantityContainedServingSize":"7.0","quantityContainedHouseHoldServingSize":"70.0","quantityContainedUnit":"GR","nutrientTypeCode":"FAT"
},{
"percentageOfDailyValueIntake":"0.8","measurementPrecision":"APPROXIMATELY","quantityContainedServingSize":"8.0","quantityContainedHouseHoldServingSize":"80.0","quantityContainedUnit":"GR","nutrientTypeCode":"SUGAR-"
},{
"percentageOfDailyValueIntake":"0.9","measurementPrecision":"APPROXIMATELY","quantityContainedServingSize":"9.0","quantityContainedHouseHoldServingSize":"90.0","quantityContainedUnit":"GR","nutrientTypeCode":"SALTEQ"
}],
"ingredientStatement": {
"de": "Zucker, Glukosesirup, Zuckersirup, Butter (3%), Salz.",
"fr": "sucre, sirop de glucose, sirop de sucre, beurre (3%), sel.",
"en": "sugar, glucose syrup, sugar syrup, butter (3%), salt."
},
"isItemReturnable": "false",
"shortDescription": {
"en": "Babbelaars"
},
"allergens": [
{
"allergenTypeCode": "BB",
"levelOfContainment": "CONTAINS"
}
],
"contactName": "LANSAEU1169",
"startAvailabilityDate": "2015-05-19",
"myattribute": "MyPostedEach",
"minimumLifespanFromTimeOfArrival": "8",
"householdServingSize": "household serving size",
"isDispatchUnit": "false",
"isBasePriceDeclarationRelevant": "false",
"allergenSpecificationAgency": "EU",
"isOrderableUnit": "false",
"allergenSpecificationName": "1169/2011",
"additives": [
{
"additiveName": "additive sample name",
"levelOfContainment": "CONTAINS"
}
],
"minimumLifespanFromTimeOfProduction": "10",
"baseUnitIndicator": "BASE_UNIT_OR_EACH",
"effectiveDate": "2015-05-19",
"servingSize": "GR",
"countryOfOrigin": "528",
"preparationType": "PRESSURE_COOKING",
"supplierItemNumber": "324324234",
"gtin": "90000000000003",
"pallets": [
{
"palletTypeCode": "37",
"height": "10.0MR",
"optionalGtin": "92000000000001",
"containedGtin": "91000000000002",
"palletTermsAndConditions": "3",
"width": "250.0CM",
"quantityOfLayersPerPallet": "5",
"palletUnitIndicator": "PALLET",
"depth": "120.0CM",
"containedAmount": "50",
"grossWeight": "1200.0KG",
"logisticsUnitStackingFactor": "10"
}
],
"barCodeType": "EAN_UCC_13_SYMBOL",
"nameOfManufacturer": "LANSA",
"compulsoryAdditivesLabelInformation": {
"de": "comp add label",
"fr": "comp add label",
"en": "comp add label"
},
"isInvoiceUnit": "false",
"isConsumerUnit": "true",
"packagingTypeCode": "CAN",
"communicationAddress": "Leliehof 26, 4841 ML PRINSENBEEK",
"itemImage": "/a/d59455129b92fb21dd00a97746a81439/babbelaars.png",
"isPackagingExemptFromRefuseObligation": "NOT_APPLICABLE"
}
Could you help me with this, I'm trying to get all keys and nested keys to create a dynamic conversion of values. Thanks in advance, Greetings Danny

Load Scatter (Line) graphs dynamically from JSON in iOS?

I'm new to corePlot and i'm having trouble to plot the graph(Line) dynamically from json when we select a particular row in UIPickerView.
Here,
Line graph with x-axis: Time as 02,03,04,.....
y-axis: temperature as 10,20,30,.....
UIPickerView consists of Date(s). for eg: we have 3 rows :
06-03-2015, 07-03-2015, 08-03-2015
and now if we select any particular row in UIPickerView i have to display line graph. I have done with Static data but now i'm getting trouble with dynamic data.
-(void)initialisePlot
{
// Start with some simple sanity checks before we kick off
if ( (self.hostingView == nil) || (self.graphData == nil) ) {
NSLog(#"TUTSimpleScatterPlot: Cannot initialise plot without hosting view or data.");
return;
}
if ( self.graph != nil ) {
NSLog(#"TUTSimpleScatterPlot: Graph object already exists.");
return;
}
// Create a graph object which we will use to host just one scatter plot.
CGRect frame = [self.hostingView bounds];
//CGRect frame = [self.hostingView bounds];
//CGRect frame = [self.hostingView frame];
self.graph = [[CPTXYGraph alloc] initWithFrame:frame] ;
//self.hostingView=[[CPTGraphHostingView alloc]initWithFrame:CGRectMake(0.0, 0.0, 900.0, 420.0)];
//self.graph = [[CPTXYGraph alloc] initWithFrame:self.hostingView.bounds];
// Add some padding to the graph, with more at the bottom for axis labels.
self.graph.plotAreaFrame.paddingTop = 20.0f;
self.graph.plotAreaFrame.paddingRight = 10.0f;
self.graph.plotAreaFrame.paddingBottom = 50.0f;
self.graph.plotAreaFrame.paddingLeft = 60.0f;
// Tie the graph we've created with the hosting view.
self.hostingView.hostedGraph = self.graph;
// If you want to use one of the default themes - apply that here.
[self.graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
// Create a line style that we will apply to the axis and data line.
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor whiteColor];
lineStyle.lineWidth = 2.0f;
// Create a text style that we will use for the axis labels.
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 14;
textStyle.color = [CPTColor whiteColor];
// Create the plot symbol we're going to use.
CPTPlotSymbol *plotSymbol = [CPTPlotSymbol crossPlotSymbol];
plotSymbol.lineStyle = lineStyle;
plotSymbol.size = CGSizeMake(8.0, 8.0);
// Setup some floats that represent the min/max values on our axis.
int xAxisMin = 0;
int xAxisMax = 20;
float yAxisMin = 0;
float yAxisMax = 50;
// We modify the graph's plot space to setup the axis' min / max values.
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(xAxisMin) length:CPTDecimalFromInt(xAxisMax-xAxisMin)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(yAxisMin) length:CPTDecimalFromFloat(yAxisMax - yAxisMin)];
// Modify the graph's axis with a label, line style, etc.
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
axisSet.xAxis.title = #"Time";
axisSet.xAxis.titleTextStyle = textStyle;
axisSet.xAxis.titleOffset = 20;
axisSet.xAxis.axisLineStyle = lineStyle;
axisSet.xAxis.majorTickLineStyle = lineStyle;
axisSet.xAxis.minorTickLineStyle = lineStyle;
axisSet.xAxis.labelTextStyle = textStyle;
axisSet.xAxis.labelOffset = 3;
axisSet.xAxis.majorIntervalLength = CPTDecimalFromInt(2);
axisSet.xAxis.minorTicksPerInterval = 1;
axisSet.xAxis.minorTickLength = 5;
axisSet.xAxis.majorTickLength = 7;
axisSet.yAxis.title = #"Temperature";
axisSet.yAxis.titleTextStyle = textStyle;
axisSet.yAxis.titleOffset = 40.0f;
axisSet.yAxis.axisLineStyle = lineStyle;
axisSet.yAxis.majorTickLineStyle = lineStyle;
axisSet.yAxis.minorTickLineStyle = lineStyle;
axisSet.yAxis.labelTextStyle = textStyle;
axisSet.yAxis.labelOffset = 3.0f;
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(10.0f);
axisSet.yAxis.minorTicksPerInterval = 1;
axisSet.yAxis.minorTickLength = 5.0f;
axisSet.yAxis.majorTickLength = 7.0f;
// Add a plot to our graph and axis. We give it an identifier so that we
// could add multiple plots (data lines) to the same graph if necessary.
CPTScatterPlot *plot = [[CPTScatterPlot alloc] init] ;
plot.dataSource = self;
plot.identifier = #"mainplot";
plot.dataLineStyle = lineStyle;
plot.plotSymbol = plotSymbol;
[self.graph addPlot:plot];
}
// Delegate method that returns the number of points on the plot
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
if ( [plot.identifier isEqual:#"mainplot"] )
{
return [self.graphData count];
}
return 0;
}
// Delegate method that returns a single X or Y value for a given plot.
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual:#"mainplot"] )
{
NSValue *value = [self.graphData objectAtIndex:index];
CGPoint point = [value CGPointValue];
// FieldEnum determines if we return an X or Y value.
if ( fieldEnum == CPTScatterPlotFieldX )
{
return [NSNumber numberWithInt:point.x];
}
else // Y-Axis
{
return [NSNumber numberWithFloat:point.y];
}
}
return [NSNumber numberWithFloat:0];
}
In viewDidLoad i'm calling this method as follows:
pickerData=[[NSArray alloc]initWithObjects:#"28-02-2015",#"01-03-2015",#"02-03-2015",#"03-03-2015",#"04-03-2015", nil];
NSMutableArray *data1 = [NSMutableArray array];
[data1 addObject:[NSValue valueWithCGPoint:CGPointMake(0, 0)]];
self.scatterPlot = [[TUTSimpleScatterPlot alloc] initWithHostingView:_graphHostingView andData:data1];
[self.scatterPlot initialisePlot];
pickerView datasource and delegate methods as follows with dynamic data:
#pragma mark PickerView DataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return pickerData.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return pickerData[row];
}
#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//PickerModal *pModal=[picDataArray objectAtIndex:row];
pickObj=[picDataArray objectAtIndex:row];
//result=[NSString stringWithFormat:#"%#",pickObj.picDate];
NSLog(#"time :%#",pickObj.picTime);
NSLog(#"temp :%#",pickObj.picTemperature);
for (int i=0; i<50; i++) {
int selectedRow=[self.myPickerView selectedRowInComponent:0];
if ((selectedRow=i)) {
NSMutableArray *data1 = [NSMutableArray array];
[data1 addObject:[NSValue valueWithCGPoint:CGPointMake([pickObj.picTime floatValue], [pickObj.picTemperature floatValue])]];
NSMutableArray *arr=[[NSMutableArray alloc]initWithArray:data1];
self.scatterPlot = [[TUTSimpleScatterPlot alloc] initWithHostingView:_graphHostingView andData:arr];
[self.scatterPlot initialisePlot];
}
}
[pickerView reloadComponent:0];
}
i'm parsing json data as :
-(void)retrieveData{
NSString *sensorTagID=#"UIUIA6767672345678910987654321";
NSMutableString *globalUrlString=[NSMutableString stringWithString:#"url"];
[globalUrlString appendString:[NSString stringWithFormat:#"?SensorTagID=%#",sensorTagID]];
NSLog(#"url string:%#",globalUrlString);
NSURL *url=[NSURL URLWithString:globalUrlString];
NSMutableURLRequest *globalRequest=[NSMutableURLRequest requestWithURL:[url standardizedURL]];
[globalRequest setHTTPMethod:#"GET"];
NSError *error = nil;
NSURLResponse *theResponse = [[NSURLResponse alloc]init];
//connecting to the server
NSData *data = [NSURLConnection sendSynchronousRequest:globalRequest returningResponse:&theResponse error:&error];
//NSData *data=[NSData dataWithContentsOfURL:url];
json=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
picDataArray=[[NSMutableArray alloc]init];
for (int i=0; i<json.count; i++) {
pickDate=[[json objectAtIndex:i]valueForKey:#"Date"];
NSLog(#"date %#",pickDate);
NSArray *getEvents=[[json objectAtIndex:i]valueForKey:#"OnDateSensorValues"];
for (NSDictionary *eventsObj in getEvents) {
pickHumidity=eventsObj[#"Humidity"];
//NSLog(#"humidity %#",pickHumidity);
pickLocationHumidity=eventsObj[#"LocationHumidity"];
//NSLog(#"locHumidity %#",pickLocationHumidity);
pickLocationTemperature=eventsObj[#"LocationTemperature"];
//NSLog(#"locTemp %#",pickLocationTemperature);
pickTemperature=eventsObj[#"Temperature"];
NSLog(#"temp %#",pickTemperature);
pickTime=eventsObj[#"Time"];
NSLog(#"time %#",pickTime);
}
pickObj=[[PickerModal alloc]initWithPicDate:pickDate andPicHumidity:pickHumidity andPicLocationHumidity:pickLocationHumidity andPicLocationTemperature:pickLocationTemperature andPicTemperature:pickTemperature andPicTime:pickTime];
[picDataArray addObject:pickObj];
}
[self.myPickerView reloadComponent:0];
}
json output as follows:
[
{
"Date": "2015-02-26",
"OnDateSensorValues": [
{
"Humidity": "49",
"LocationHumidity": "49",
"LocationTemperature": "45",
"Temperature": "45",
"Time": "10"
},
{
"Humidity": "48",
"LocationHumidity": "48",
"LocationTemperature": "44",
"Temperature": "44",
"Time": "11"
},
{
"Humidity": "47",
"LocationHumidity": "47",
"LocationTemperature": "43",
"Temperature": "43",
"Time": "12"
},
{
"Humidity": "46",
"LocationHumidity": "46",
"LocationTemperature": "42",
"Temperature": "42",
"Time": "13"
},
{
"Humidity": "45",
"LocationHumidity": "45",
"LocationTemperature": "41",
"Temperature": "41",
"Time": "14"
}
]
},
{
"Date": "2015-02-27",
"OnDateSensorValues": [
{
"Humidity": "29",
"LocationHumidity": "29",
"LocationTemperature": "25",
"Temperature": "25",
"Time": "6"
},
{
"Humidity": "28",
"LocationHumidity": "28",
"LocationTemperature": "24",
"Temperature": "24",
"Time": "7"
},
{
"Humidity": "27",
"LocationHumidity": "27",
"LocationTemperature": "23",
"Temperature": "23",
"Time": "8"
},
{
"Humidity": "26",
"LocationHumidity": "26",
"LocationTemperature": "22",
"Temperature": "22",
"Time": "9"
},
{
"Humidity": "25",
"LocationHumidity": "25",
"LocationTemperature": "21",
"Temperature": "21",
"Time": "10"
}
]
},
{
"Date": "2015-02-28",
"OnDateSensorValues": [
{
"Humidity": "31",
"LocationHumidity": "31",
"LocationTemperature": "35",
"Temperature": "35",
"Time": "22"
},
{
"Humidity": "32",
"LocationHumidity": "32",
"LocationTemperature": "36",
"Temperature": "36",
"Time": "21"
},
{
"Humidity": "33",
"LocationHumidity": "33",
"LocationTemperature": "37",
"Temperature": "37",
"Time": "20"
},
{
"Humidity": "34",
"LocationHumidity": "34",
"LocationTemperature": "38",
"Temperature": "38",
"Time": "19"
},
{
"Humidity": "35",
"LocationHumidity": "35",
"LocationTemperature": "39",
"Temperature": "39",
"Time": "18"
}
]
},
{
"Date": "2015-03-01",
"OnDateSensorValues": [
{
"Humidity": "12",
"LocationHumidity": "12",
"LocationTemperature": "16",
"Temperature": "16",
"Time": "2"
},
{
"Humidity": "13",
"LocationHumidity": "13",
"LocationTemperature": "17",
"Temperature": "17",
"Time": "1"
},
{
"Humidity": "14",
"LocationHumidity": "14",
"LocationTemperature": "18",
"Temperature": "18",
"Time": "2"
},
{
"Humidity": "15",
"LocationHumidity": "15",
"LocationTemperature": "19",
"Temperature": "19",
"Time": "3"
},
{
"Humidity": "16",
"LocationHumidity": "16",
"LocationTemperature": "20",
"Temperature": "20",
"Time": "4"
}
]
},
{
"Date": "2015-03-02",
"OnDateSensorValues": [
{
"Humidity": "32",
"LocationHumidity": "32",
"LocationTemperature": "36",
"Temperature": "36",
"Time": "20"
},
{
"Humidity": "33",
"LocationHumidity": "33",
"LocationTemperature": "37",
"Temperature": "37",
"Time": "21"
},
{
"Humidity": "34",
"LocationHumidity": "34",
"LocationTemperature": "38",
"Temperature": "38",
"Time": "22"
},
{
"Humidity": "35",
"LocationHumidity": "35",
"LocationTemperature": "39",
"Temperature": "39",
"Time": "23"
},
{
"Humidity": "36",
"LocationHumidity": "36",
"LocationTemperature": "40",
"Temperature": "40",
"Time": "24"
}
]
}
]
from here i would like to take temp,time values and show on graph. But i'm able to plot only one point on the graph. How to get all time and temp values on the graph?....Please help me as i'm struggling with the concept since 1week.

Resources