Parsing Twitter API Search Response in Swift with TwitterKit - json

I am trying to get only the Text, Username, and later the profile image of the tweets returned by a twitter API call, using their reference: Twitter API: Search Tweets. I've gotten an authentic response, and can parse the JSON by Status, but the contents of each status seems to be in a format that is not JSON, as each "key" isn't in quotes and uses an equals sign to associate with it's value.
Does anyone know how I can take the 'status' object I end up with and pull any of the values out? Even just converting it into a string, and I can just use string parsing to pull it out. This is simply for a learning project and it does not need to be fancy.
Also, any explanation as to why the 'JSON' I'm looking at doesn't actually follow normal JSON format, would be helpful.
I'm using TwitterKit to make the request. I am fairly new to swift, and JSON parsing. Here is my code:
let client = TWTRAPIClient()
let statusesShowEndpoint = "https://api.twitter.com/1.1/search/tweets.json"
let params = ["q": "#formlabs", "result_type": "recent", "include_entities": "false", "count": "3"]
var clientError : NSError?
let request = client.urlRequest(withMethod: "GET", url: statusesShowEndpoint, parameters: params, error: &clientError)
client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
if connectionError != nil {
print("Error: \(String(describing: connectionError))")
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
//print(json)
let statuses = json!["statuses"] as? [Any]
let status = statuses![0]
print(status)
} catch let jsonError as NSError {
print("json error: \(jsonError.localizedDescription)")
}
}
Here is output when I print out one status, which I can only seem to cast as Any. When I try to cast as a String, it comes back nil.
{
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Thu Oct 26 21:22:50 +0000 2017";
"favorite_count" = 1;
favorited = 0;
geo = "<null>";
id = 923661218778247169;
"id_str" = 923661218778247169;
"in_reply_to_screen_name" = mesgreene;
"in_reply_to_status_id" = 923623395849367552;
"in_reply_to_status_id_str" = 923623395849367552;
"in_reply_to_user_id" = 71702948;
"in_reply_to_user_id_str" = 71702948;
"is_quote_status" = 0;
lang = en;
metadata = {
"iso_language_code" = en;
"result_type" = recent;
};
place = {
attributes = {
};
"bounding_box" = {
coordinates = (
(
(
"-117.282538",
"32.53962"
),
(
"-116.9274403",
"32.53962"
),
(
"-116.9274403",
"33.0804044"
),
(
"-117.282538",
"33.0804044"
)
)
);
type = Polygon;
};
"contained_within" = (
);
country = "United States";
"country_code" = US;
"full_name" = "San Diego, CA";
id = a592bd6ceb1319f7;
name = "San Diego";
"place_type" = city;
url = "https://api.twitter.com/1.1/geo/id/a592bd6ceb1319f7.json";
};
"retweet_count" = 0;
retweeted = 0;
source = "Twitter Web Client";
text = "#mesgreene #HeroForgeMinis #formlabs Formlabs said I would have to apply a primer to it, then I could paint it with\U2026 ";
truncated = 1;
user = {
"contributors_enabled" = 0;
"created_at" = "Wed Jan 16 03:07:48 +0000 2013";
"default_profile" = 0;
"default_profile_image" = 0;
description = "Bridge Designer. Alternative Delivery Expert. ProjectWise Dude. Guru in all things BIM/CAD. And I moonlight as patient support for people with Crohn's / IBD";
entities = {
description = {
urls = (
);
};
url = {
urls = (
{
"display_url" = "/Zv8TKR";
"expanded_url" = "https:///Zv8TKR";
indices = (
0,
23
);
url = "https:///mOUvQ9iP7w";
}
);
};
};
"favourites_count" = 3530;
"follow_request_sent" = "<null>";
"followers_count" = 238;
following = "<null>";
"friends_count" = 232;
"geo_enabled" = 1;
"has_extended_profile" = 1;
id = 1093947408;
"id_str" = 1093947408;
"is_translation_enabled" = 0;
"is_translator" = 0;
lang = en;
"listed_count" = 29;
location = "San Diego, CA";
name = "SoCal BIM Guru";
notifications = "<null>";
"profile_background_color" = 000000;
"profile_background_image_url" = "http://abs.twimg.com/images/themes/theme1/bg.png";
"profile_background_image_url_https" = "https://abs.twimg.com/images/themes/theme1/bg.png";
"profile_background_tile" = 0;
"profile_banner_url" = "https://pbs.twimg.com/profile_banners/1093947408/1499732034";
"profile_image_url" = "http://pbs.twimg.com/profile_images/885923732178337792/qnWdWM_J_normal.jpg";
"profile_image_url_https" = "https://pbs.twimg.com/profile_images/885923732178337792/qnWdWM_J_normal.jpg";
"profile_link_color" = 1B95E0;
"profile_sidebar_border_color" = 000000;
"profile_sidebar_fill_color" = 000000;
"profile_text_color" = 000000;
"profile_use_background_image" = 0;
protected = 0;
"screen_name" = ReubenJStone;
"statuses_count" = 1304;
"time_zone" = "Pacific Time (US & Canada)";
"translator_type" = none;
url = "https:///mOUvQ9iP7w";
"utc_offset" = "-25200";
verified = 0;
};
}

The correct answer is to use the new Codeable framework: https://medium.com/swiftly-swift/swift-4-decodable-beyond-the-basics-990cc48b7375

Related

Array of dictionaries to JSON in Swift

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.

JSON data keep on returning nil

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)

Getting index of an object in returns nil

I'm trying to get the index of an object (user), in a one to many relationship. It returns nil.
import Foundation
class Groups : NSObject{
var groupName: String?
var UsersInGroup = [BackendlessUser]()
var ownerId: String?
var objectId : String?
}
func getIndex() {
self.backendless.userService.getPersistentUser()
let user = self.backendless.userService.currentUser
var dataStore = backendless.data.of(Groups.ofClass())
dataStore.findID(
"B52F6BEA-79F8-A58B-FF15-AF840BCB2A00",
response: { (result: AnyObject!) -> Void in
var LookingForGroupJoining = result as! Groups
// LookingForGroupJoining.UsersInGroup.append(user)
let index = LookingForGroupJoining.UsersInGroup.indexOf(user)
print("This is the index number : \(index)")
print("This is the user : \(user)")
print("These are all the values of the UsersInGroup : \(LookingForGroupJoining.UsersInGroup)")
dataStore.save(
LookingForGroupJoining,
response: { (result: AnyObject!) -> Void in
let GroupJoining = result as! Groups
print("Group has been saved: \(GroupJoining.groupName)")
},
error: { (fault: Fault!) -> Void in
print("Server reported an error (1): \(fault)")
})
print("Group has been found: \(LookingForGroupJoining.objectId)")
},
error: { (fault: Fault!) -> Void in
print("Server reported an error (2): \(fault)")
})
}
Here is the console output
This is the index number : nil
This is the user : <BackendlessUser> {
"__meta" = "{\"relationRemovalIds\":{},\"selectedProperties\":[\"__updated__meta\",\"password\",\"created\",\"name\",\"___class\",\"ownerId\",\"updated\",\"objectId\",\"email\"],\"relatedObjects\":{}}";
created = "2016-03-07 06:06:40 +0000";
email = "test#test.com";
lastLogin = "2016-03-11 04:30:01 +0000";
name = "<null>";
objectId = "4A955ADD-7991-1AF8-FFEF-3754587B2300";
ownerId = "<null>";
updated = "<null>";
"user-token" = "18C87E0E-2BB3-DB1D-FF63-3CD5FE003200";
}
These are all the values of the UsersInGroup : [<BackendlessUser> {
"___class" = Users;
created = "2016-03-07 03:45:05 +0000";
email = "lekan.adeyeri#gmail.com";
name = test;
objectId = "0EB97FF9-FBF1-2E7E-FF30-160BB6CFFC00";
ownerId = "<null>";
password = "<null>";
updated = "2016-03-18 22:33:02 +0000";
}, <BackendlessUser> {
"___class" = Users;
created = "2016-03-07 06:06:40 +0000";
email = "test#test.com";
name = "<null>";
objectId = "4A955ADD-7991-1AF8-FFEF-3754587B2300";
ownerId = "<null>";
password = "<null>";
updated = "2016-03-18 22:33:02 +0000";
}, <BackendlessUser> {
"___class" = Users;
created = "2016-03-06 04:15:27 +0000";
email = "tesbhjbj#ttt.tyy";
name = "<null>";
objectId = "570CD92B-74EB-1325-FF8F-B866CB6CB400";
ownerId = "<null>";
password = "<null>";
updated = "2016-03-18 22:33:02 +0000";
}, <BackendlessUser> {
"___class" = Users;
created = "2016-03-05 04:50:14 +0000";
email = "test#testmail.test";
name = test;
objectId = "A0831585-716E-B027-FF37-539497748400";
ownerId = "<null>";
password = "<null>";
updated = "2016-03-18 22:33:02 +0000";
}, <BackendlessUser> {
"___class" = Users;
created = "2016-03-05 14:54:53 +0000";
email = "test1#testmail.test";
name = test;
objectId = "C8A47476-E5D2-B84D-FF5A-2EB605040400";
ownerId = "<null>";
password = "<null>";
updated = "2016-03-18 22:33:02 +0000";
}]
I'm trying to get the index of an object (user), in a one to many relationship. It returns nil.
Found a workaround
func leavingGroup() {
self.backendless.userService.getPersistentUser()
let user = self.backendless.userService.currentUser
var dataStore = backendless.data.of(Groups.ofClass())
dataStore.findID(
"B52F6BEA-79F8-A58B-FF15-AF840BCB2A00",
response: { (result: AnyObject!) -> Void in
var LookingForGroupJoining = result as! Groups
var groupList = LookingForGroupJoining.UsersInGroup.description
// ā€œCleanedā€ groupList of unnecessary data and created groupListCleaned
var groupListCleaned: String = groupList.stringByReplacingOccurrencesOfString("\"", withString: "").stringByReplacingOccurrencesOfString("<BackendlessUser> {", withString: "").stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString("___class=Users;", withString: "").stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).stringByReplacingOccurrencesOfString("},", withString: "").stringByReplacingOccurrencesOfString("]", withString: "").stringByReplacingOccurrencesOfString("}", withString: "").stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("created=", withString: "").stringByReplacingOccurrencesOfString("email=", withString: "").stringByReplacingOccurrencesOfString("name=", withString: "").stringByReplacingOccurrencesOfString("objectId=", withString: "").stringByReplacingOccurrencesOfString("ownerId=", withString: "").stringByReplacingOccurrencesOfString("password=", withString: "").stringByReplacingOccurrencesOfString("updated=", withString:"").stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Converting groupListClean from a string to an array called arrayofUsers, where the arrays values are anything between whitespace, so the string cookie = ā€œchocolate cake hotteaā€ would be an array [ā€œchocolateā€, ā€œcakeā€, ā€œhottea"]
let arrayofUsers: Array = groupListCleaned.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
// Converting arrayofUsers into string, and replacing some characters. I did the filter here instead of groupList because it produced different results, and I preferred these results here.
var groupListClean2: String = arrayofUsers.joinWithSeparator("").stringByReplacingOccurrencesOfString(";", withString: ",")
// Once Iā€™ve cleaned the string completely, Iā€™m turning it into an array again called arrayofUsers2. Iā€™m separating everything with a coma.
var arrayofUsersData: Array = groupListClean2.componentsSeparatedByString(",")
// Iā€™m getting the index number of the current user's objectId in the data. It pulls out the index of one property belonging to one user, in a list of properties belonging to many users.
var indexnumber = arrayofUsersData.indexOf(user.objectId)
var indexnumber2 = indexnumber
var index = 0
// Since objectIds are always in the same location (7 sway from the next), if its less than really 6 (I set 3 to be safe), then its the users index is 0. If its not, then Iā€™ll keep subtracting by 7, and incrementing the index value each time I subtract. Each user can be identified by jumping 7 indexes, this shows me how many times I have to do that jump, the amount of times is where the user is.
if indexnumber2 <= 3 {
index = 0
} else {
repeat {
indexnumber2 = indexnumber2! - 7
index = index + 1
} while indexnumber2 > 3
}
LookingForGroupJoining.UsersInGroup.removeAtIndex(index)
dataStore.save(
LookingForGroupJoining,
response: { (result: AnyObject!) -> Void in
let GroupJoining = result as! Groups
print("Group has been saved: \(GroupJoining.groupName)")
},
error: { (fault: Fault!) -> Void in
print("Server reported an error (1): \(fault)")
})
print("Group has been found: \(LookingForGroupJoining.objectId)")
},
error: { (fault: Fault!) -> Void in
print("Server reported an error (2): \(fault)")
})
}

Need Help Parsing JSON with Swift using Alamofire

I'm trying to retrieve an article from Google news and parse it using Swift. I'm using Alamofire. I know the basics of what to when parsing, but the output seems kind of complex and I don't know how to access the "title" value. Any help would be appreciated. Thanks!
Here is the JSON Output:
responseData = {
cursor = {
currentPageIndex = 0;
estimatedResultCount = 445755633;
moreResultsUrl = "http://news.google.com/nwshp?oe=utf8&ie=utf8&source=uds&q=sports&hl=en&start=0";
pages = (
{
label = 1;
start = 0;
},
{
label = 2;
start = 1;
},
{
label = 3;
start = 2;
},
{
label = 4;
start = 3;
},
{
label = 5;
start = 4;
},
{
label = 6;
start = 5;
},
{
label = 7;
start = 6;
},
{
label = 8;
start = 7;
}
);
};
results = (
{
GsearchResultClass = GnewsSearch;
clusterUrl = "http://news.google.com/news/story?ncl=dO-ivvqeXteuGKMAkRap55WyAkOvM&hl=en&ned=us";
content = "sportsbook The Third Circuit Court of Appeals will rehear a potentially landmark case Wednesday brought by the NCAA, NFL, MLB, NBA and NHL claiming a New Jersey gambling law enacted in 2014 that repealed certain prohibitions on sports wagering in ...";
image = {
originalContextUrl = "http://lawnewz.com/sports/new-jersey-lawsuit-could-make-sports-betting-legal-across-the-country/";
publisher = LawNewz;
tbHeight = 53;
tbUrl = "http://t0.gstatic.com/images?q=tbn:ANd9GcQ2htg8w11Y6_4ClDD80jdQN6VtGGMya5KomCyLCgzVjOsyMJLVdkffcSg9";
tbWidth = 80;
url = "http://lawnewz.com/wp-content/uploads/2016/02/800px-Las_Vegas_sportsbook-351x234.jpg";
};
language = en;
location = "";
publishedDate = "Tue, 16 Feb 2016 10:47:00 -0800";
publisher = LawNewz;
relatedStories = (
{
language = en;
location = "";
publishedDate = "Tue, 16 Feb 2016 07:34:35 -0800";
publisher = ESPN;
signedRedirectUrl = "http://news.google.com/news/url?sa=T&ct2=us&fd=S&url=http://espn.go.com/chalk/story/_/id/14785562/chalk-previewing-latest-new-jersey-sports-betting-appeal&cid=52779048299261&ei=5OHDVujuMfOmwQHOn53oAg&usg=AFQjCNH7bfL6cWr1Q8PKgPOkQIP7ZRUoRw";
title = "Future of sports betting once again at stake in New Jersey";
titleNoFormatting = "Future of sports betting once again at stake in New Jersey";
unescapedUrl = "http://espn.go.com/chalk/story/_/id/14785562/chalk-previewing-latest-new-jersey-sports-betting-appeal";
url = "http%3A%2F%2Fespn.go.com%2Fchalk%2Fstory%2F_%2Fid%2F14785562%2Fchalk-previewing-latest-new-jersey-sports-betting-appeal";
}
);
signedRedirectUrl = "http://news.google.com/news/url?sa=T&ct2=us&fd=S&url=http://lawnewz.com/sports/new-jersey-lawsuit-could-make-sports-betting-legal-across-the-country/&cid=52779048299261&ei=5OHDVujuMfOmwQHOn53oAg&usg=AFQjCNHAqRF8uPjG1Ki7yxjz0sATv05i6A";
title = "New Jersey Lawsuit Could Make Sports Betting Legal Across the Country";
titleNoFormatting = "New Jersey Lawsuit Could Make Sports Betting Legal Across the Country";
unescapedUrl = "http://lawnewz.com/sports/new-jersey-lawsuit-could-make-sports-betting-legal-across-the-country/";
url = "http%3A%2F%2Flawnewz.com%2Fsports%2Fnew-jersey-lawsuit-could-make-sports-betting-legal-across-the-country%2F";
}
);
};
responseDetails = "";
responseStatus = 200;
}
I'm really confused by this because it doesn't look like most examples I've seen online.
add SwiftyJSON from github and do the stuff below
import SwiftyJSON
func parseJson() {
Alamofire.request(.POST, "urlString", parameters: parameter, encoding: .JSON)
.responseJSON { response in
//Check Response
if response.result.isFailure == true {
return
}
let json = JSON(response.result.value!)
let cursorEntity = json["Cursor"]
let currentIndex = json["cursor"].currentPageIndex
let pageEntity = json["cursor"]["pages"]
let resultsEntity = json["cursor"]["results"]
}
}
Use Alamofire with SwiftyJSON plugin called Alamofire-SwiftyJSON
Alamofire.request(.GET,
urlString,
parameters: ["foo": "bar"])
.responseSwiftyJSON({ (request, response, json, error) in
var cursor = json["cursor"]
// do your stuff ..
})
As #cem olcay mentioned above use the Alamofire and SwiftyJSON. Try the below code. But haven't tested.
func getData() {
Alamofire.request(.GET, "YOUR_URL_STRING")
.responseJSON { response in
let json = JSON(data: response)
if let title = json[0]["relatedStories"][0]["title"].string {
//Now you got your value
}
}
}

Embedded json data in swift three levels

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)
}
}
}