Convert .rtf file into NSDictionary or NSArray - swift

I have a file (.rtf) that contains data that looks like:
[
{
"Symbol": "PIH",
"Name": "1347 Property Insurance Holdings, Inc.",
"LastSale": "6.8299",
"MarketCap": 41717882.9375,
"ADR TSO": "n/a",
"IPOyear": "2014",
"Sector": "Finance",
"Industry": "Property-Casualty Insurers",
"Summary Quote": "http://www.nasdaq.com/symbol/pih",
"FIELD10": ""
},
{
"Symbol": "FLWS",
"Name": "1-800 FLOWERS.COM, Inc.",
"LastSale": "9.27",
"MarketCap": 606557031.66,
"ADR TSO": "n/a",
"IPOyear": "1999",
"Sector": "Consumer Services",
"Industry": "Other Specialty Stores",
"Summary Quote": "http://www.nasdaq.com/symbol/flws",
"FIELD10": ""
},
{
"Symbol": "FCCY",
"Name": "1st Constitution Bancorp (NJ)",
"LastSale": "12.99",
"MarketCap": 103169203.98,
"ADR TSO": "n/a",
"IPOyear": "n/a",
"Sector": "Finance",
"Industry": "Savings Institutions",
"Summary Quote": "http://www.nasdaq.com/symbol/fccy",
"FIELD10": ""
}
]
Now, I would like to convert this data into something (NSDictionary, NSArray, etc.) that I can use to easily access the data. Any help would be appreciated.

guard let path = NSBundle.mainBundle().pathForResource("fileName", ofType: "txt") else {
return nil
}
do {
let content = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
return content
} catch _ as NSError {
return nil
}
Save the .rtf file into a location (say desktop).
Read the file from that location

Related

MS Graph API- End-point to read email messages with header information from outlook account

I am using the below endpoint to read mail messages from a given mail folders but I see the message does not contain header information.
end point- https://graph.microsoft.com/v1.0/me/mailFolders/{folderid}messages/?$orderby=sentDateTime
Response looks like-
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('55f7b855-44a8-46c2-908a-00ff4d54c46e')/mailFolders('AQMkAGYyOTI1Yzc5LTFlZjctNDlhYy1hMWQzLTA1MjY0ZmRkADBkZTAALgAAA--el_XftXZKt0YdPN_913sBAFL-3e9Uo9BKmUKAmISlmIAAAAIBCQAAAA%3D%3D')/messages",
"value": [
{
"#odata.etag": "W/\"CQAAABYAAABS/93vVKPQSplCgJiEpZiAAAAMRZRE\"",
"id": "AAMkAGYyOTI1Yzc5LTFlZjctNDlhYy1hMWQzLTA1MjY0ZmRkMGRlMABGAAAAAAD-3pfl37V2SrdGHTzfvdd7BwBS-93vVKPQSplCgJiEpZiAAAAAAAEJAABS-93vVKPQSplCgJiEpZiAAAAMTZWmAAA=",
"createdDateTime": "2021-08-02T12:47:39Z",
"lastModifiedDateTime": "2021-08-02T12:47:42Z",
"changeKey": "CQAAABYAAABS/93vVKPQSplCgJiEpZiAAAAMRZRE",
"categories": [],
"receivedDateTime": "2021-08-02T12:47:40Z",
"sentDateTime": "2021-08-02T12:47:39Z",
"hasAttachments": false,
"internetMessageId": "<MAZPR01MB5442E2218F9D377BD1D514E4E9EF9#MAZPR01MB5442.INDPRD01.PROD.OUTLOOK.COM>",
"subject": "rr",
"bodyPreview": "rr",
"importance": "normal",
"parentFolderId": "AQMkAGYyOTI1Yzc5LTFlZjctNDlhYy1hMWQzLTA1MjY0ZmRkADBkZTAALgAAA--el_XftXZKt0YdPN_913sBAFL-3e9Uo9BKmUKAmISlmIAAAAIBCQAAAA==",
"conversationId": "AAQkAGYyOTI1Yzc5LTFlZjctNDlhYy1hMWQzLTA1MjY0ZmRkMGRlMAAQAKmsc6svyzlHuJr_l4TQwX4=",
"conversationIndex": "AQHXh5yTqaxzqy/LOUe4mv6XhNDBfg==",
"isDeliveryReceiptRequested": false,
"isReadReceiptRequested": false,
"isRead": true,
"isDraft": false,
"webLink": "https://outlook.office365.com/owa/?ItemID=AAMkAGYyOTI1Yzc5LTFlZjctNDlhYy1hMWQzLTA1MjY0ZmRkMGRlMABGAAAAAAD%2F3pfl37V2SrdGHTzfvdd7BwBS%2F93vVKPQSplCgJiEpZiAAAAAAAEJAABS%2F93vVKPQSplCgJiEpZiAAAAMTZWmAAA%3D&exvsurl=1&viewmodel=ReadMessageItem",
"inferenceClassification": "focused",
"body": {
"contentType": "html",
"content": "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><meta content=\"text/html; charset=iso-8859-1\"><style type=\"text/css\" style=\"display:none\"><!--p{margin-top:0;margin-bottom:0}--></style></head><body dir=\"ltr\"><div style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0)\">rr<br></div></body></html>"
},
"sender": {
"emailAddress": {
"name": "some name",
"address": "some address"
}
},
"from": {
"emailAddress": {
"name": "some name",
"address": "some address"
}
},
"toRecipients": [
{
"emailAddress": {
"name": "some name",
"address": "some address"
}
}
],
"ccRecipients": [],
"bccRecipients": [],
"replyTo": [],
"flag": {
"flagStatus": "notFlagged"
}
}
]
}
Earlier we used java.mail API to do the same and used to get it like
javax.mail.Message message= ;
Enumeration headers = message.getAllHeaders();
Is there any way to achieve this using an MS graph API?
If you want the Internet Message headers then you need to include that in the Select Parameter as the Graph doesn't return it as a default property eg
https://graph.microsoft.com/v1.0/me/messages/?$select=internetMessageHeaders

Firestore read document

I am trying to read a document from Firestore but I face this problem
Error Domain=FIRFirestoreErrorDomain Code=14 "Failed to get document because the client is offline." UserInfo={NSLocalizedDescription=Failed to get document because the client is offline.}
Note : the collection and the document are existing
I am use Firebase/Firestore version 1.17.1
could anyone help me please?!
This is an example of getting data with Cloud Firestore (source: firebase.google.com)
Firstly create data:
let citiesRef = db.collection("cities")
citiesRef.document("SF").setData([
"name": "San Francisco",
"state": "CA",
"country": "USA",
"capital": false,
"population": 860000,
"regions": ["west_coast", "norcal"]
])
citiesRef.document("LA").setData([
"name": "Los Angeles",
"state": "CA",
"country": "USA",
"capital": false,
"population": 3900000,
"regions": ["west_coast", "socal"]
])
citiesRef.document("DC").setData([
"name": "Washington D.C.",
"country": "USA",
"capital": true,
"population": 680000,
"regions": ["east_coast"]
])
citiesRef.document("TOK").setData([
"name": "Tokyo",
"country": "Japan",
"capital": true,
"population": 9000000,
"regions": ["kanto", "honshu"]
])
citiesRef.document("BJ").setData([
"name": "Beijing",
"country": "China",
"capital": true,
"population": 21500000,
"regions": ["jingjinji", "hebei"]
])
Then the following example shows how to retrieve the contents of a single document using get():
let docRef = db.collection("cities").document("SF")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
This may be as well be an error if you are using firebase.firestore(), with firebase.database() it is working well. 😘

URLSessionDataTask ignores URLRequest's httpMethod property

I'm having this bizarre problem in which I cannot do a simple POST request to a REST service I do not control based on GraphQL.
The problem is that no matter what I set in the httpMethod property of the URLRequest class, it always uses GET instead.
I have done a few tests to discard some problems. For example, I set up a header in the Request and I can verify that the header is being sent to the server (verified with Charles Proxy).
This is the code you can paste and run in a Playground:
import PlaygroundSupport
import Foundation
PlaygroundPage.current.needsIndefiniteExecution = true
let url = URL(string: "http://graphql.anilist.co/")!
let internalSession = URLSession(configuration: .default)
var request = URLRequest(url: url)
request.httpMethod = "POST"
let headers = ["content-type": "application/json"]
request.allHTTPHeaderFields = headers
request.httpBody =
"""
{"query":"query (\n\t$season: MediaSeason,\n\t$year: Int,\n\t$format: MediaFormat,\n\t$excludeFormat: MediaFormat,\n\t$status: MediaStatus,\n\t$minEpisodes: Int,\n\t$page: Int,\n){\n\tPage(page: $page) {\n\t\tpageInfo {\n\t\t\thasNextPage\n\t\t\ttotal\n\t\t}\n\t\tmedia(\n\t\t\tseason: $season\n\t\t\tseasonYear: $year\n\t\t\tformat: $format,\n\t\t\tformat_not: $excludeFormat,\n\t\t\tstatus: $status,\n\t\t\tepisodes_greater: $minEpisodes,\n\t\t\tisAdult: false,\n\t\t\ttype: ANIME,\n\t\t\tsort: TITLE_ROMAJI,\n\t\t) {\n\t\t\t\nid\nidMal\ntitle {\n\tromaji\n\tnative\n\tenglish\n}\nstartDate {\n\tyear\n\tmonth\n\tday\n}\nendDate {\n\tyear\n\tmonth\n\tday\n}\nstatus\nseason\nformat\ngenres\nsynonyms\nduration\npopularity\nepisodes\nsource(version: 2)\ncountryOfOrigin\nhashtag\naverageScore\nsiteUrl\ndescription\nbannerImage\ncoverImage {\n\textraLarge\n\tcolor\n}\ntrailer {\n\tid\n\tsite\n\tthumbnail\n}\nexternalLinks {\n\tsite\n\turl\n}\nrankings {\n\trank\n\ttype\n\tseason\n\tallTime\n}\nstudios(isMain: true) {\n\tnodes {\n\t\tid\n\t\tname\n\t\tsiteUrl\n\t}\n}\nrelations {\n\tedges {\n\t\trelationType(version: 2)\n\t\tnode {\n\t\t\tid\n\t\t\ttitle {\n\t\t\t\tromaji\n\t\t\t\tnative\n\t\t\t\tenglish\n\t\t\t}\n\t\t\tsiteUrl\n\t\t}\n\t}\n}\n\nairingSchedule(\n\tnotYetAired: true\n\tperPage: 2\n) {\n\tnodes {\n\t\tepisode\n\t\tairingAt\n\t}\n}\n\n\t\t}\n\t}\n}","variables":{"season": WINTER,"year": 2019,"page": 1, "perPage": 100}}
""".data(using: .utf8)
print("THE REQUEST \(String(describing: request.httpMethod))")
let task = internalSession.dataTask(with: request, completionHandler: { (data, response, error) in
if let e = error {
print("ERROR: \(e)")
} else if let response = response as? HTTPURLResponse {
print("THE RESPONSE: \(response)")
let json = try! JSONSerialization.jsonObject(with: data!, options: [])
print(json)
}
})
task.resume()
(Please ignore all the forced unwrap optionals and forced try!, this is test code).
Expected Result
I expect the web service to return a JSON similar to this (simplified):
{
"data": {
"Page": {
"pageInfo": {
"hasNextPage": true,
"total": 81
},
"media": [
{
"id": 102882,
"idMal": 37956,
"title": {
"romaji": "3D Kanojo: Real Girl 2",
"native": "3D彼女 リアルガール 2",
"english": "Real Girl 2"
},
"startDate": {
"year": 2019,
"month": 1,
"day": 9
},
"endDate": {
"year": null,
"month": null,
"day": null
},
"status": "RELEASING",
"season": "WINTER",
"format": "TV",
"genres": [
"Romance",
"Slice of Life",
"Comedy"
],
"synonyms": [],
"duration": 23,
"popularity": 3298,
"episodes": 12,
"source": "MANGA",
"countryOfOrigin": "JP",
"hashtag": "#3D彼女リアルガール #3D彼女",
"averageScore": 61,
"siteUrl": "https://anilist.co/anime/102882",
"description": "The second season of <i>3D Kanojo</i>.",
"bannerImage": null,
"coverImage": {
"extraLarge": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/nx102882-lKp3ExWNzoE6.jpg",
"color": "#e4bb93"
},
"trailer": {
"id": "x6yokzp",
"site": "dailymotion",
"thumbnail": "https://www.dailymotion.com/thumbnail/video/x6yokzp"
},
"externalLinks": [
{
"site": "Official Site",
"url": "http://www.3dkanojo-anime.com/"
},
{
"site": "Twitter",
"url": "https://twitter.com/3Dkanojo_anime"
}
],
"rankings": [
{
"rank": 16,
"type": "RATED",
"season": null,
"allTime": false
},
{
"rank": 19,
"type": "POPULAR",
"season": null,
"allTime": false
},
{
"rank": 16,
"type": "RATED",
"season": "WINTER",
"allTime": false
},
{
"rank": 15,
"type": "POPULAR",
"season": "WINTER",
"allTime": false
}
],
"studios": {
"nodes": [
{
"id": 346,
"name": "Hoods Entertainment",
"siteUrl": "https://anilist.co/studio/346"
}
]
},
"relations": {
"edges": [
{
"relationType": "PREQUEL",
"node": {
"id": 100526,
"title": {
"romaji": "3D Kanojo: Real Girl",
"native": "3D彼女 リアルガール",
"english": "Real Girl"
},
"siteUrl": "https://anilist.co/anime/100526"
}
},
{
"relationType": "SOURCE",
"node": {
"id": 80767,
"title": {
"romaji": "3D Kanojo: Real Girl",
"native": "3D彼女 〈リアルガール〉",
"english": "Real Girl"
},
"siteUrl": "https://anilist.co/manga/80767"
}
}
]
},
"airingSchedule": {
"nodes": [
{
"episode": 7,
"airingAt": 1550595540
},
{
"episode": 8,
"airingAt": 1551200340
}
]
}
}
]
}
}
}
Obtained Result
Instead, I get this:
{
"data": null,
"errors": [
{
"message": "Not Found.",
"hint": "Use POST request to access graphql subdomain.",
"status": 404
}
]
}
The service complains that the request is a GET request and should be POST, and I am explicitly telling URLRequest to use POST instead. If you look at the request in Charles or another proxy, you will indeed see that the request is being done as a GET request, and the httpBody property is being discarded. If you edit the headers and add another header, like so:
let headers = ["content-type": "application/json", "foo": "bar"]
You will see in your proxy that the header is being properly sent.
The only conclusion I can arrive is that there is an internal problem with URLSessionDataTask that forces to do GET requests only. I tried changing it to to a download task, but the same problem is happening. So there must be a problem with my code, but I cannot find it.
EDIT:
Per request, this is the request Postman uses. I have exported the request to CURL to make it easily importable.
curl -X POST \
https://graphql.anilist.co/ \
-H 'Content-Type: application/json' \
-H 'Postman-Token: 49d7e55e-35c2-4a3c-82f0-4eccb1250fc0' \
-H 'cache-control: no-cache' \
-d '{"query":"query (\n\t$season: MediaSeason,\n\t$year: Int,\n\t$format: MediaFormat,\n\t$excludeFormat: MediaFormat,\n\t$status: MediaStatus,\n\t$minEpisodes: Int,\n\t$page: Int,\n){\n\tPage(page: $page) {\n\t\tpageInfo {\n\t\t\thasNextPage\n\t\t\ttotal\n\t\t}\n\t\tmedia(\n\t\t\tseason: $season\n\t\t\tseasonYear: $year\n\t\t\tformat: $format,\n\t\t\tformat_not: $excludeFormat,\n\t\t\tstatus: $status,\n\t\t\tepisodes_greater: $minEpisodes,\n\t\t\tisAdult: false,\n\t\t\ttype: ANIME,\n\t\t\tsort: TITLE_ROMAJI,\n\t\t) {\n\t\t\t\nid\nidMal\ntitle {\n\tromaji\n\tnative\n\tenglish\n}\nstartDate {\n\tyear\n\tmonth\n\tday\n}\nendDate {\n\tyear\n\tmonth\n\tday\n}\nstatus\nseason\nformat\ngenres\nsynonyms\nduration\npopularity\nepisodes\nsource(version: 2)\ncountryOfOrigin\nhashtag\naverageScore\nsiteUrl\ndescription\nbannerImage\ncoverImage {\n\textraLarge\n\tcolor\n}\ntrailer {\n\tid\n\tsite\n\tthumbnail\n}\nexternalLinks {\n\tsite\n\turl\n}\nrankings {\n\trank\n\ttype\n\tseason\n\tallTime\n}\nstudios(isMain: true) {\n\tnodes {\n\t\tid\n\t\tname\n\t\tsiteUrl\n\t}\n}\nrelations {\n\tedges {\n\t\trelationType(version: 2)\n\t\tnode {\n\t\t\tid\n\t\t\ttitle {\n\t\t\t\tromaji\n\t\t\t\tnative\n\t\t\t\tenglish\n\t\t\t}\n\t\t\tsiteUrl\n\t\t}\n\t}\n}\n\nairingSchedule(\n\tnotYetAired: true\n\tperPage: 2\n) {\n\tnodes {\n\t\tepisode\n\t\tairingAt\n\t}\n}\n\n\t\t}\n\t}\n}","variables":{"year":2019,"season":"WINTER","page":1, "limit": 12}}'
Only difference I am seeing here is http:// in your Playground and https:// in your Postman.
So just replace http:// with https:// in your Playground.

Firebase, Retrieving Data: Find all Titles that have 'Status' as 'Open' in Swift

Main mission is to find all Titles that have 'Status' as 'Open'
I want to get all the favorTit to an array to be used in indexPath.row
func retrieveQuery(){
var i = 0
queryRef.queryOrderedByChild("status").queryEqualToValue("Open")
.observeEventType(.ChildAdded, withBlock:
{ snapshot in
i++
self.antal = snapshot.children.allObjects.count
print(self.antal)
print(snapshot.value.objectForKey("favorTit")!)
print(i)
})
}
Firebase data
https://api.myjson.com/bins/4n5rn
{
"categories": [{
"altText": "T.ex. Städning, Disk, Tvätt, Matlagning",
"title": "Hushåll"
}, {
"altText": "T.ex. ",
"title": " "
}, {
"altText": " ",
"title": " "
}, {
"altText": " ",
"title": " "
}, {
"altText": " ",
"title": " "
}, {
"altText": " ",
"title": " "
}, {
"altText": " ",
"title": " "
}],
"favors": {
"1": {
"catId": 1,
"favorBudget": 212121,
"favorDes": "Gfdgsfdsg",
"favorDueDate": "Today",
"favorGeo": [-7.090910999999999, 107.668887],
"favorLocation": ["West Java, Indonesia"],
"favorTit": "Rätt",
"status": "Open",
"user": "2872e074-e45a-4d7a-a9c7-83fad641aa62",
"workCompletion": "In person"
},
"2": {
"catId": 1,
"favorBudget": 4000,
"favorDes": "Gfdgf",
"favorDueDate": "Today",
"favorGeo": [34.506668, -81.948334],
"favorLocation": ["Laurens County Airport, Laurens, SC 29360, USA"],
"favorTit": "Rätt",
"status": "Open",
"user": "2872e074-e45a-4d7a-a9c7-83fad641aa62",
"workCompletion": "In person"
},
"3": {
"catId": 1,
"favorBudget": 4000,
"favorDes": "Gfdgf",
"favorDueDate": "Today",
"favorGeo": [34.506668, -81.948334],
"favorLocation": ["Laurens County Airport, Laurens, SC 29360, USA"],
"favorTit": "Rätt",
"status": "Ongoing",
"user": "2872e074-e45a-4d7a-a9c7-83fad641aa62",
"workCompletion": "In person"
},
"7fd547be-7836-42e2-a74f-2f2a39baee43": {
"favorTit": "Test",
"favors": {
"furniture assmebly": {
"favorBudget": 60000,
"favorDes": "Assemly My ikea",
"favorDueDate": "Today",
"favorGeo": [39.0311755, -77.5283463],
"favorLocation": ["Polen Farm Blvd, Ashburn, VA 20148, USA"],
"favorTit": "Den ska bli fixad kom snabbt",
"workCompletion": "In person"
},
"handyman": {
"favorBudget": 43434,
"favorDes": "Install TV-Mount",
"favorDueDate": "Today",
"favorGeo": [49.0068901, 8.4036527],
"favorLocation": ["Karlsruhe, Germany"],
"favorTit": "JAllah",
"workCompletion": "In person"
},
"photography": {
"favorBudget": 6000,
"favorDes": "Jag vill ha ett album med bilder på mig och omgivningen💪 Du ska inte säga mycket under bröllopet men det ska vara vackra bilder",
"favorDueDate": "Within a week",
"favorGeo": [55.6178043, 12.98939],
"favorLocation": ["Krankajen 36, 211 12 Malmö, Sverige"],
"favorTit": "take a photo of my wedding",
"workCompletion": "In person"
},
"trädgård": {
"favorBudget": 2000,
"favorDes": "Jag vill ha den klippt med en sax",
"favorDueDate": "Within a week",
"favorGeo": [35.86166, 104.195397],
"favorLocation": ["China"],
"favorTit": "Klipp min gräsmatta",
"workCompletion": "In person"
}
},
"status": "Done"
}
},
"users": {
"2872e074-e45a-4d7a-a9c7-83fad641aa62": {
"email": "fille382#gmail.com",
"name": "lol",
"phone": "123567890",
"provider": "password"
},
"5f0fb39e-620a-4cd1-9e6a-2b7ae9baaf71": {
"email": "lol#gmail.com",
"name": "Gunn Bellander",
"phone": "0735158548",
"provider": "password"
},
"7fd547be-7836-42e2-a74f-2f2a39baee43": {
"about": "Johan my name is Filip Bellander and i am creating this beautiful app right now the about page is here so the user can quickly reach its target by writing about himself and his completions ",
"comments": {
"4354352": {
"comment": "He did everything even cleaned up after himself",
"stars": 3,
"tasktitle": "Do everything"
},
"423489054": {
"comment": "Yes very nice",
"stars": 1,
"tasktitle": "call my phone"
},
"5435486956": {
"comment": "It was very clean",
"stars": 3,
"tasktitle": "Clean room"
},
"54643654654": {
"comment": "He did a great job wiping all whipcream from the luggage",
"stars": 4,
"tasktitle": "Whipe dat"
}
},
"completed": 90,
"email": "test#gmail.com",
"name": "Filip Bellander",
"phone": "0735158548",
"posted": 81,
"provider": "password",
"rating": 5,
"reviews": 1337,
"skills": "App programmer, Visual designer DriversDriverslicenseDriverslicenseDriverslicenseDriverslicenselicense no"
},
"bdc6c3f8-764a-4468-825a-408f53695b24": {
"email": "Elisabet.bellander#gmail.com",
"name": "Elisabet Bellander",
"phone": "0721645504",
"provider": "password"
}
}
}
From your code you should already have the Open Titles array in your snapshot.
if let result = snapshot.children.allObjects as? [FIRDataSnapshot] {
self.items = result
}
Then your TableView will depend on how you are implementing it. There is some examples here and here.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
...
let cellDict = items[indexPath.row]
...
return cell
}
I was able to make an array by inserting the string at index 0 everytime it runs by using the code below
queryRef.queryOrderedByChild("status").queryEqualToValue("Open")
.observeEventType(.ChildAdded, withBlock:
{ snapshot in
self.antal = snapshot.children.allObjects.count
print(self.antal)
var titles = snapshot.value.objectForKey("favorTit") as! String
var description = snapshot.value.objectForKey("favorDes") as! String
var budget = snapshot.value.objectForKey("favorBudget") as! Double
self.openTitles.insert(titles, atIndex: 0)
self.openDescription.insert(description, atIndex: 0)
self.openBudget.insert(budget, atIndex: 0)
print(self.openTitles)
print(self.openDescription)
})

SwiftyJSON and Dynamic Named Objects

Problem: Attempting to consume a JSON payload which contains a dynamic Object name. Since the names of these objects are not sequential or derived from a pattern, I'm unable to travers the payload with SwiftyJSON. A sample of the dynamic objects looks like this denoted in bold:
"180A": {
"id": "180A",
"label": "Oceanside Gate",
"path": "North",
"index": "1"
},
"195C": {
"id": "195C",
"label": "Dune Beach Gate",
"path": "North",
"index": "2"
},
"211F": {
"id": "211F",
"label": "Sunset Harbor Gate",
"path": "North",
"index": "3"
}
Sample JSON Payload:
{
"Direction": {
"NorthGates": {
"180A": {
"id": "180A",
"label": "Oceanside Gate",
"path": "North",
"index": "1"
},
"195C": {
"id": "195C",
"label": "Dune Beach Gate",
"path": "North",
"index": "2"
},
"211F": {
"id": "211F",
"label": "Sunset Harbor Gate",
"path": "North",
"index": "3"
}
}
}
}
Using SwiftyJSON I'm able to successfully print the label of a known Object, such as "180A":
DataManager.getTopAppsDataFromFileWithSuccess { (data) -> Void in
let json = JSON(data: data)
if let gateLabel = json["Direction"]["NorthGates"]["180A"]["label"].stringValue {
//output: "Oceanside Gate"
println("NSURLSession: \(gateLabel)")
}
}
Since the dynamic object names are not static, I'm unable to use the pre-defined object names in the code above to locate the label value. The following attempts return nil values:
//stringValue = nil
if let gateLabel = json["Direction"]["NorthGates"][0].stringValue {
println("NSURLSession: \(gateLabel)")
}
//stringValue = nil
if let gateLabel = json["Direction"]["NorthGates"][0]["label"].stringValue {
println("NSURLSession: \(gateLabel)")
}
This is the solution:
if let gates:[String: JSON] = json["Direction"]["NorthGates"].dictionaryValue {
for item in gates {
println("Dynamic Object Gate Name: \(item.0)") //Gate Name
println(item.1["label"].stringValue) //Gate Label
println(item.1["path"].stringValue) //Gate Path
println(item.1["index"].stringValue) //Gate Index
}
}