I am using Twitter-Kit/Fabric to get a response from the twitter api. It returns a JSON of the following format - https://dev.twitter.com/rest/reference/get/search/tweets
My query is - https://api.twitter.com/1.1/search/tweets.json?q=""&geocode=lat,long,radius&count=15
I need to extract the text and the coordinates from the JSON to plot those tweets on a map.
What am I doing wrong with the following code - ?
Twitter.sharedInstance().APIClient.sendTwitterRequest(request) {
(response, data, connectionError) -> Void in
if (connectionError == nil) {
var jsonError : NSError?
let parsedResult =
NSJSONSerialization.JSONObjectWithData(data,
options: nil,
error: &jsonError) as NSDictionary
println(parsedResult)
if let tweets = parsedResult["statuses"] as? NSDictionary {
for tweetsDict in tweets {
let title = tweetsDict["text"] as NSString
println("text: \(title)")
let coordinates = tweetsDict["coordinates"]
println("coordinates: \(coordinates)\n")
}
}else {
println("Error: \(connectionError)")
}
}
My code runs till println(parsedResult) as I'm getting a valid response from the twitter api. However I'm having trouble extracting the tweet text from the JSON response.
If you are using Fabric, you can create tweet objects from the response using TWTRTweet method
+ (NSArray *)tweetsWithJSONArray:(NSArray *)array;
It creates an array of TWTRTweet instances from the array of Twitter API JSON response.
NSArray *tweetData = [TWTRTweet tweetsWithJSONArray:responseFromTwitter];
[tableview reloadData];
You can use tweet objects to populate in tableview in cellForRowAtIndexPath. To return a tweet cell,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = @"TweetCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
TWTRTweet *tweet = twitterResponse[indexPath.row];
[(TWTRTweetTableViewCell *)cell configureWithTweet:tweet];
return cell;
}
EDIT
In Swift, you can do as:
// Create an array of tweet model objects from a JSON array
tweetData = TWTRTweet.tweetsWithJSONArray(responseFromTwitter)
tableView.reloadData()
//create Tweet cells
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let tweet = tweetData[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(tweetTableReuseIdentifier, forIndexPath: indexPath) as TWTRTweetTableViewCell
cell.configureWithTweet(tweet)
return cell
}
Hope it helps!
Reference taken from here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With