CellTableView With Twitter API won't Display Data - ios

I'm currently doing a practice for twitter API. Currently, i had a problem to populate a search hashtag results to tableview cellForRowAtIndexPath method. Below is my code.
My Header Code :
#interface TableViewController : UITableViewController<UITableViewDataSource,UITableViewDelegate> #property (nonatomic,strong) NSArray *array; #end
My Implementation Code :
#import "TableViewController.h"
#import <Social/Social.h>
#import <Accounts/Accounts.h>
#interface TableViewController ()
#end
#implementation TableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self getDataFromTwitter];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSDictionary *dataDictionary = [self.array objectAtIndex:indexPath.row];
// NSLog(#"data result: %#", self.array);
cell.textLabel.text = dataDictionary[#"text"];
return cell;
}
- (void)getDataFromTwitter {
// 1. set an URL
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1.1/search/tweets.json"];
// 2. set NSMutableArray For Parameter
NSMutableDictionary *parameter = [[NSMutableDictionary alloc] init];
[parameter setObject:#"%23MH370" forKey:#"q"];
[parameter setObject:#"10" forKey:#"text"];
[parameter setObject:#"popular" forKey:#"result_type"];
//3. set ACAccountStore & ACAccountType
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted == YES) {
NSArray *accountArray = [accountStore accountsWithAccountType:accountType];
if ([accountArray count] > 0) {
ACAccount *twitterAccount = [accountArray lastObject];
// guna slrequest to get data from twitter
SLRequest *getRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:url parameters:parameter];
// set twitter account
[getRequest setAccount:twitterAccount];
[getRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *output = [NSString stringWithFormat:#"HTTP response status : %i", [urlResponse statusCode]];
NSLog(#"Output : %#", output);
self.array = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
if (self.array.count != 0) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
NSLog(#"search result: %#", self.array);
});
}
}];
}
}
}];
}
#end
I got a problem now when i always got a crash when i'm running the app and here is result from my console.
2014-03-12 19:57:11.990 twitterSearch[3069:a0b] -[__NSCFDictionary objectAtIndexedSubscript:]: unrecognized selector sent to instance 0xa45fd00
2014-03-12 19:57:11.992 twitterSearch[3069:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndexedSubscript:]: unrecognized selector sent to instance 0xa45fd00'

This error means that you are dealing with a NSArray as NSDictionary, most likely you are getting dictionary here not array:
self.array = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];

Related

Getting a json file from a website into UITableview with Objective C

I'm attempting to get a json file from a website into UITableview with Objective C.
As I'm not an advanced coder please excuse my crude coding tecniques.
I have a .json file uploaded to my webspace. The File is formatted as so:
"JSONDATA":[
{
"name": "ABC",
"details": "DEF"
},
{
"name": "UVW",
"details": "XYZ"
}
]
my .h looks like:
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
IBOutlet UITableView *myTableView;
}
#property (strong, nonatomic) IBOutlet UITableView *myTableView;
#end
the .m code
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrName;
NSMutableArray *arrDetails;
NSString *responseString;
}
#end
#implementation ViewController
#synthesize myTableView;
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"ViewDidLoad");
[self fetchData];
[myTableView reloadData];
}
-(void)fetchData
{
NSLog(#"GetJsonResponse Fired");
NSURL *URL = [NSURL URLWithString:#"http://myWebsite.com/json/myJsonFile.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSLog(#"URLRequest = %#",request);
/////////////////////////////////////////////////////////////////// Nothing Below Here Fires/////////////////////////////////////////////////
// [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:ourBlock];
[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error)
{
// Block Body
NSLog(#"response = %#",response);
NSLog(#"block Body");
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"GetJsonDict%#",jsonDict);
NSArray *arr = jsonDict[#"JSONFILE"];
NSLog(#"jasoDict = %#",arr);
self->arrName = [[NSMutableArray alloc]init];
self->arrDetails = [[NSMutableArray alloc]init];
//arrValue = [[NSMutableArray alloc]init];
for(int i=0;i<[arr count];i++)
{
NSString *strName = [arr[i]objectForKey:#"NAME"];
NSString *strCode = [arr[i]objectForKey:#"CODE"];
// NSString *strValue = [arr[i]objectForKey:#"VALUE"];
NSLog(#"The strName is - %#",strName);
NSLog(#"The strCode is - %#", strCode);
// NSLog(#"The strValue is - %#", strValue);
[self->arrName addObject:strName];
[self->arrDetails addObject:strCode];
// [arrValue addObject:strValue];
NSLog(#"The arrName is - %#",self->arrName);
NSLog(#"The arrDetails is - %#", self->arrDetails);
// NSLog(#"The arrValue is - %#", arrValue);
}
}];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrName.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strCell = #"Cell";
// UITableViewCell *cell = [UITableView dequeueReusableCellWithIdentifier:strCell];
UITableViewCell *cell = [myTableView dequeueReusableCellWithIdentifier:strCell forIndexPath:indexPath];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strCell];
}
cell.textLabel.text = arrName[indexPath.row];
cell.detailTextLabel.text = arrDetails[indexPath.row];
return cell;
}
#end
I can't seem to put all the pieces together and get any data through to parse.
The NSLog is telling me:
2020-03-09 14:13:42.605558-0500 jsonFromWeb[27389:1317924] ViewDidLoad
2020-03-09 14:13:42.605802-0500 jsonFromWeb[27389:1317924] GetJsonResponse Fired
2020-03-09 14:13:42.606118-0500 jsonFromWeb[27389:1317924] URLRequest = <NSURLRequest: 0x6000001f8cc0> { URL: http://mywebsite.com/json/myJsonFile.json }
Where is this thing derailing? I can't get any data out of the URLResponse.
Thanks so much.
You have to resume the data task and you have to reload the table view inside the completion block on the main thread
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
...
}
dispatch_async(dispatch_get_main_queue(), ^{
[myTableView reloadData];
});
}] resume];

Objective-c TableView Refresh With dispatch_sync error

Hello I have working simple tableview json parsing codes. But i want to do reload tableview in background everytime i added dispatch_sync codes but don't working my codes under.
NSArray * jsonArray;
NSMutableArray * array1;
- (void)viewDidLoad {
[super viewDidLoad];
NSURL * url = [NSURL URLWithString:#"http://bla.com/test2.json"];
NSURLRequest * urlReq = [NSURLRequest requestWithURL:url];
NSError * error;
NSData * data = [NSURLConnection sendSynchronousRequest:urlReq returningResponse:nil error:&error];
NSDictionary * jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",jsonDict);
jsonArray = [jsonDict objectForKey:#"worldpopulation"];
NSLog(#"%#",jsonArray);
array1 =[[NSMutableArray alloc]init];
}
- (void)main
{
dispatch_sync(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return jsonArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellid=#"CustomCell";
CustomTableViewCell *cell=(CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid];;
if(cell==nil)
{
cell=[[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];
}
for ( NSDictionary * dict in jsonArray) {
NSString * country = [dict objectForKey:#"country"];
[array1 addObject:country];
}
cell.nameLabel.text= [array1 objectAtIndex:indexPath.row];
return cell;
}
Main.m
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[]) {
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
I added only needed codes . I need to fix it .
Thanks for your help !
First, performing synchronous network operations on the main thread is a bad idea - it will make your app UI 'freeze' until the operation completes, which in the case of a slow (or no) network could be a long time.
Secondly, you should move the loading code into its own function that you call from viewDidLoad - this way you can easily call it again if you want to reload the data.
Thirdly, your cellForRowAtIndexPath is iterating your entire jsonArray for each cell to no purpose.
Finally, NSURLConnection is deprecated in iOS 9 so you should migrate to NSURLSession if you are targeting iOS7 and later (if you want to run on iOS prior to iOS 7 then you will need to keep using NSURLConnection)
I would suggest the following:
#interface MyViewController () <UITableViewDelegate,UITableViewDataSource>
#property (strong,nonatomic) NSArray *jsonArray;
#end
#implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.jsonArray=[NSArray new];
[self loadJSON];
}
-(void)loadJSON {
NSURL * url = [NSURL URLWithString:#"http://bla.com/test2.json"];
NSURLSession *session=[NSURLSession sharedSession];
[session dataTaskWithRequest:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error!=nil) {
NSLog(#"Something went wrong:%#",error);
} else {
NSError *jsonError;
NSDictionary * jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonEerror];
if (jsonError != nil) {
NSLog(#"JSON isn't right:%#",jsonError);
} else {
self.jsonArray = jsonDict[#"worldpopulation"];
dispatch_async(dispatch_get_main_queue(),^{
[self.tableview reloadData];
});
}
}];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.jsonArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellid=#"CustomCell";
CustomTableViewCell *cell=(CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid forIndexPath:indexPath];;
NSDictionary *entryDict=self.jsonArray[indexPath.row];
NSString *countryName=entryDict[#"country"];
cell.nameLabel.text= countryName;
return cell;
}

iOS JSON parsing from web to a UITableView

I'm experiencing a problem with my code but I'm not sure why it's doing this. It's just giving me an error saying JSON Error. The UITableView never gets filled with anything. I'm not very experienced with iOS, so any help is appreciated.
//
// ViewController.m
// Westmount Procrastinator
//
// Created by Saleem on 10/25/13.
// Copyright (c) 2013 Saleem Al-Zanoon. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UIWebView *webView;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *fullURL = #"********";
NSURL *url2 = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url2];
[_webView loadRequest:requestObj];
self.title = #"News";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"****************"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self]; // NSString * urlString = [NSString stringWithFormat:#"http://salespharma.net/westmount/get_all_products.php"];
// NSURL * url = [NSURL URLWithString:urlString];
// NSData * data = [NSData dataWithContentsOfURL:url];
// NSError * error;
// NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// NSLog(#"%#",json);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
//news = [responseDict objectAtIndex:0];
// [mainTableView reloadData];
if ([responseDict isKindOfClass:[NSArray class]]) {
news = responseDict;
[mainTableView reloadData];
} else {
// Looks like here is some part of the problem but I don't know why.
NSLog(#"JSON Error.");
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Could not contact server!" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [news count];
}
NSString *_getString(id obj)
{
return [obj isKindOfClass:[NSString class]] ? obj : nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
}
cell.textLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:#"Issue"]);
cell.detailTextLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:#"Name"]);
return cell;
}
#end
How the JSON looks on the internet:
{
"Issues":[
{
"Issue":"2",
"Link":"google.com",
"Name":"Ios Test"
},
{
"Issue":"3",
"Link":"Yahoo",
"Name":"iOS test 2"
}
],
"success":1
}
Edit: sorry for not being clear in my question, The app does not crash but fails to load the data into the database in the log it puts this up:
2013-10-26 10:26:41.670 Westmount Procrastinator[2490:70b] JSON Error.
2013-10-26 10:26:41.671 Westmount Procrastinator[2490:70b] Server Data:
{"Issues":[{"Issue":"2","Link":"google.com","Name":"Ios Test"}],"success":1}
The goal of the application to contact a database download a list of Issues of a newspaper then list them in the list view.. Then allowing the user to click on the issues and download them.
Edit I added more to the JSON to help explain.
From your sample JSON structure it does not appear to be a NSArray. It is NSDictionary instead. So, while you are parsing JSON data save it in NSDictionary and not in NSArray. Also, change your IF condition afterwards.
Importantly, if your tableview is reading data from an NSArray of NSDictionaries then I would say put this NSDictionary into an NSArray and pass it to table view. Also, check from server side what is the output in case they are multiple dictionaries in which you need to handle accordingly. So essentially there are couple of more lines you need to induce here or else ask data provider (server side) to send NSArray in all cases.
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
if ([responseDict isKindOfClass:[NSDictionary class]]) {
NSArray *tableArray = [NSArray arrayWithArray:responseDict[#"Issues"]];
}
Now use tableArray to populate your table.
Issues is an array of dictionaries, so you should ask for the dictionary at the indexpath.row, then use objectForKey to pull the appropriate value from that dictionary.
NSDictionary *myDict = #{#"Issues": #[#{#"Issue": #"2",
#"Link": #"google.com",
#"Name": #"Ios Test"},
#{#"Issue": #"3",
#"Link": #"Yahoo",
#"Name": #"iOS test 2"}],
#"success": #"1"};
NSArray *issues = [myDict objectForKey:#"Issues"];
[issues enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"Issue: %# Link: %# Name: %#", [obj objectForKey:#"Issue"], [obj objectForKey:#"Link"], [obj objectForKey:#"Name"]);
}];
Will return:
2013-10-26 16:42:43.572 Jsontest[43803:303] Issue: 2 Link: google.com Name: Ios Test
2013-10-26 16:42:43.573 Jsontest[43803:303] Issue: 3 Link: Yahoo Name: iOS test 2

Making Profile Photos show up using Twitter API 1.1

We're working on an iOS 7 Twitter client. I haven't worked with the the Twitter API much and what I did was before 1.1.
Could somebody please help us get the profile photos loading on our application's Timeline?
Our code is below.
Here is our .h file:
#import <UIKit/UIKit.h>
#import <Accounts/Accounts.h>
#import <Social/Social.h>
#import <Twitter/Twitter.h>
#interface FirstViewController : UIViewController <UITableViewDataSource , UITableViewDelegate> {
UIRefreshControl *myRefreshControl;
}
#property (nonatomic) IBOutlet UITableView *timelineTableView;
#property (nonatomic) NSArray *timelineArray;
#end
and here is our .m for the application's timeline.
#interface FirstViewController ()
#end
#implementation FirstViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self getTimeline];
myRefreshControl = [[UIRefreshControl alloc]init];
myRefreshControl.tintColor = [UIColor blackColor];
[myRefreshControl setAttributedTitle:[[NSAttributedString alloc]initWithString:#"Pull to Refresh"]];
[myRefreshControl addTarget:self action:#selector(refreshTimeline) forControlEvents: UIControlEventValueChanged];
[self.timelineTableView addSubview:myRefreshControl];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)getTimeline
{
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[account requestAccessToAccountsWithType:accountType
options:nil completion:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
NSArray *arrayOfAccounts = [account
accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts lastObject];
NSURL *requestURL = [NSURL URLWithString:#"http://api.twitter.com/1/statuses/home_timeline.json"];
NSMutableDictionary *parameters =
[[NSMutableDictionary alloc] init];
[parameters setObject:#"200" forKey:#"count"];
[parameters setObject:#"1" forKey:#"include_entities"];
SLRequest *postRequest = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET
URL:requestURL parameters:parameters];
postRequest.account = twitterAccount;
[postRequest performRequestWithHandler:
^(NSData *responseData, NSHTTPURLResponse
*urlResponse, NSError *error)
{
self.timelineArray = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:&error];
if (self.timelineArray.count != 0) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.timelineTableView reloadData];
});
}
}];
}
} else {
}
}];
}
-(void)refreshTimeline
{
[self getTimeline];
[self.timelineTableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.timelineArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSDictionary *tweet = self.timelineArray[[indexPath row]];
cell.textLabel.text = [[tweet objectForKey:#"user"]objectForKey:#"name"];
cell.detailTextLabel.text = [tweet objectForKey:#"text"];
cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL: [[tweet objectForKey:#"user"]objectForKey:#"profile_image_url"]]];
return cell;
}
#end
The response of :
http://api.twitter.com/1/statuses/home_timeline.json
will return home feeds. It contains a user key in it , you have to access that and get the profile image by profile_image_url.
Handling response in array of dictionaries will solve your problem and each dictionary will have the user key which contains profile_image_url.
Your call to the api is referencing version 1. I would suggest reviewing the info at https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline and examining the response format.
You can drill down the response to arrive at the 'user' object and get the profile image from there.

iOS [__NSCFString > objectForKeyedSubscript:]:

I am trying to implement a tableview with a twitter feed into my iOS app. I have followed tutorials and am able to get the users twitter feed. I found the url for a hash tag but when implemented get an error:
'NSInvalidArgumentException', reason: '-[__NSCFString
objectForKeyedSubscript:]: unrecognized selector sent to instance
0xa0b7e20'
I have tried to do some research but all attempts failed. Any advice would be great. Thank you.
.h
#import <UIKit/UIKit.h>
#import <Social/Social.h>
#import <Accounts/Accounts.h>
#interface ViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *tweetTableView;
#property (nonatomic, copy) NSArray *dataSource;
-(IBAction)refresh:(id)sender;
#end
.m
#implementation ViewController
- (void)getTimeLine {
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[account requestAccessToAccountsWithType:accountType
options:nil completion:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
NSArray *arrayOfAccounts = [account
accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts lastObject];
/* NSString * kTwitterHashtag = #"#nasa";
NSString * kTwitterUsername = #"";
// Looking for #kTwitterHashtag or #kTwitterUsername
NSString *urlString = [[[#"http://search.twitter.com/search.json?q=%23" stringByAppendingString:(NSString *)kTwitterHashtag]
stringByAppendingString:#"+OR+%40"] stringByAppendingString:(NSString *)kTwitterUsername];
NSURL *requestURL = [NSURL URLWithString:urlString];
*/
NSURL *requestURL = [NSURL URLWithString:#"http://api.twitter.com/1/statuses/home_timeline.json"];
NSMutableDictionary *parameters =
[[NSMutableDictionary alloc] init];
[parameters setObject:#"20" forKey:#"count"];
[parameters setObject:#"1" forKey:#"include_entities"];
SLRequest *postRequest = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET
URL:requestURL parameters:parameters];
postRequest.account = twitterAccount;
[postRequest performRequestWithHandler:
^(NSData *responseData, NSHTTPURLResponse
*urlResponse, NSError *error)
{
self.dataSource = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:&error];
if (self.dataSource.count != 0) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.tweetTableView reloadData];
NSLog(#"_dataSource.count %d",_dataSource.count);
for(NSDictionary * tweet in _dataSource){
NSLog(#"tweet : %#",tweet[#"text"]);
}
});
}
}];
}
} else {
// Handle failure to get account access
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
_tweetTableView = [[UITableView alloc] init];
_dataSource = [[NSArray alloc] init];
[self getTimeLine];
}
-(IBAction)refresh:(id)sender{
[self getTimeLine];
[self.tweetTableView reloadData];
}
#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _dataSource.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tweetTableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *tweet = _dataSource[[indexPath row]];
NSLog(#"tweet : %#",tweet);
cell.textLabel.text = tweet[#"text"];
return cell;
}
#end
self.dataSource = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
This is returning a string... but you are assigning it to an NSArray!

Resources