AFNetworking 2.0 and simple JSON - xcode

I'm trying to use AFNetworking 2.0 consuming a simple json, the result from the json is:
{
"solicitudId": "61898",
"estado": "Atendida",
"tipoPago": null,
"monto": 23,
"mayorDerecho": 0,
"sistema": "SPRL"
}
I defined a class (solicitud.h solicitud.m) like this:
#interface SolicitudNSDictionary : NSDictionary
- (NSString *)solicitudId;
- (NSString *)estado;
- (NSString *)tipoPago;
- (NSNumber *)monto;
- (NSNumber *)mayorDerecho;
- (NSString *)sistema;
#end
the json is call here without error
- (IBAction)jsonButton:(id)sender {
// 1
NSString *string = [NSString stringWithFormat:#"%#solicitud?id=61898&from=MOVIL&ip=172.9.1.14", BaseURLString];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
self.solicitud = (NSDictionary *)responseObject;
self.title = #"JSON Retrieved";
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
#end
My problem is I don't know how implement the tableview from the NSDictionary, on the cellForRowAtIndexPath i tried but i have not luck.
I declared in the #interface
#property(strong) NSDictionary *solicitud;
and this variable is set here
// 3
self.solicitud = (NSDictionary *)responseObject;
Where I get error is
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"cellName";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *solicitudTmp = nil;
solicitudTmp = [self.solicitud];
// You will add code here later to customize the cell, but it's good for now.
cell.textLabel.text = [self.solicitudTmp solicitudId];
return cell;
}
At this line
solicitudTmp = [self.solicitud];

solicitudTmp = [self.solicitud]; is a syntax error.
Objective-C messages exist in the format [receiver message]. The code above is missing a message.
What you probably intended was:
cell.textLabel.text = [self.solicitud valueForKey:#"solicitudId"];
That said, there's a lot of other really questionable stuff going on in this question:
SolicitudNSDictionary, as a model, should be a subclass of NSObject that has an initializer that takes a dictionary (NSDictionary should not be subclassed)
You should let AFNetworking take care of turning URL parameters into a query string.
Your operation code could be improved by using an AFHTTPRequestOperationManager, instead of constructing requests yourself.
I would strongly encourage you to look at some additional resources before going forward. Apple's Developer Site has a number of programming guides and other reference material to help get you started.

Related

NSMutableArray have error empty array

i have some problem with NSMutablearray and JSON parse.
So what i doing? A make parse from JSON and send to my TableViewCell.
I have my code:
h:
{
NSMutableData *webdata;
NSURLConnection *connection;
NSMutableArray *array;
NSMutableArray *array2;
NSTimer *timer;
}
m:
{
[super ViewDidload]
[[self tableTrack] setDelegate:self];
[[self tableTrack] setDataSource:self];
array = [[NSMutableArray alloc] init];
array2 = [[NSMutableArray alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(plistGet) userInfo:nil repeats:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webdata setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"error load");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSDictionary *playlist =[allDataDictionary objectForKey:#"playlist"];
for (NSDictionary *diction in playlist) {
NSDictionary *artist = [diction objectForKey:#"artist"];
NSDictionary *song = [diction objectForKey:#"song"];
NSString *name = [artist objectForKey:#"name"];
NSString *namesong = [song objectForKey:#"name"];
[array addObject:name];
[array2 addObject:namesong];
}
[[self tableTrack]reloadData];
}
-(void)plistGet {
[array removeAllObjects];
[array2 removeAllObjects];
NSURL *url = [NSURL URLWithString:#"http://plist.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webdata = [[NSMutableData alloc]init];
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
// return [array2 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]autorelease];
}
cell.textLabel.text = [array2 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [array objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor colorWithRed:(50/255.0) green:(200/255.0) blue:(255/255.0) alpha:1];
[tableTrack setBackgroundView:nil];
tableTrack.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.font=[UIFont fontWithName: #"Helvetica" size:11];
UIFont *myFont = [ UIFont fontWithName: #"Arial" size: 9.0 ];
cell.textLabel.font = myFont;
self.tableTrack.separatorStyle = UITableViewCellSeparatorStyleNone;
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorView.layer.borderColor = [UIColor darkGrayColor].CGColor;
separatorView.layer.borderWidth = 0.5;
[cell.contentView addSubview:separatorView];
return cell;
}
All work very good but after 5 or 3 minutes i have error and my app crashed.
Error:
2013-06-21 12:32:41.502 EuropaPlusUA[651:707] * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
* First throw call stack:
(0x353f188f 0x37798259 0x3533a9db 0xfa9d5 0x32e85efb 0x32e84fd9 0x32e84763 0x32e28f37 0x353501fb 0x32220aa5 0x322206bd 0x32224843 0x3222457f 0x3221c4b9 0x353c5b1b 0x353c3d57 0x353c40b1 0x353474a5 0x3534736d 0x36fe3439 0x32e53cd5 0xf8843 0xf87d0)
terminate called throwing an exception
What is it? Help please.
Your problem is that you probably do another plistget method after that 3-5 minutes. That method will throw away all objects from your array. During the time your data is getting loaded and the time you cleared your array, the table datasource is empty, however you are trying to get this object from index 0. This is why your crash happens.
The solution however is simple. Do not call the removeAllObjects method at all.
Simply replace the array with the contents that you will retrieve.
Replace mechanic that you will need to do the moment you get the data from your server:
NSMutableArray *tempDataArray = [[NSMutableArray alloc] init];
//put retrieved data from your web call in the tempDataArray
array = tempDataArray;
me thinks the only objectAtIndex is here.
cell.detailTextLabel.text = [array objectAtIndex:indexPath.row];
seems likely array was emptied by plistget
[array removeAllObjects];
Totumus Maximus is right.
If you just need to bridge the gap between getting clearing the arrays and reloading the data why not try NOT deleting them until the new data is ready? Then just replace them
Alternatively make a copy of them first (say to backUpArray and backUpArray2) and then check to see if you have data in array/array2 (something like if([array count]) or if (array) {...) before you try and load the cell.
If you have nothing in the arrays use [backUpArray lastObject] to give you some data for the (brief ?) time until the arrays are reloaded.

Crash Occurring on First Launch When populating core data database

I keep getting an error in the debugger for my application saying,
2013-06-23 16:07:15.826 collection view recipies[5681:c07] -[NSManagedObject length]: unrecognized selector sent to instance 0x9495280
2013-06-23 16:07:15.827 collection view recipies[5681:c07] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject length]: unrecognized selector sent to instance 0x9495280'
* First throw call stack:
(0x26ac012 0x1517e7e 0x27374bd 0x269bbbc 0x269b94e 0x2b11c4 0x16d80a 0x4464 0x64f2da 0x6508f4 0x652b91 0x19c2dd 0x152b6b0 0x18eefc0 0x18e333c 0x18eeeaf 0x23b2bd 0x183b56 0x18266f 0x182589 0x1817e4 0x18161e 0x1823d9 0x1852d2 0x22f99c 0x17c574 0x17c76f 0x17c905 0x185917 0x14996c 0x14a94b 0x15bcb5 0x15cbeb 0x14e698 0x2c06df9 0x2c06ad0 0x2621bf5 0x2621962 0x2652bb6 0x2651f44 0x2651e1b 0x14a17a 0x14bffc 0x1e9d 0x1dc5)
libc++abi.dylib: terminate called throwing an exception
In My application delegate, if check to see if the application is being launched for the first time, and if it is, I then add several image paths to the core data structure.
In AppDelegate.m under ApplicationDidFinishLaunchingWithOptions,
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"HasLaunchedOnce"])
{
// app already launched
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"HasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
// This is the first launch ever
NSArray *mainDishImages = [NSArray arrayWithObjects:#"egg_benedict.jpg", #"full_breakfast.jpg", #"ham_and_cheese_panini.jpg", #"ham_and_egg_sandwich.jpg", #"hamburger.jpg", #"instant_noodle_with_egg.jpg", #"japanese_noodle_with_pork.jpg", #"mushroom_risotto.jpg", #"noodle_with_bbq_pork.jpg", #"thai_shrimp_cake.jpg", #"vegetable_curry.jpg", nil];
NSArray *drinkDessertImages = [NSArray arrayWithObjects:#"angry_birds_cake.jpg", #"creme_brelee.jpg", #"green_tea.jpg", #"starbucks_coffee.jpg", #"white_chocolate_donut.jpg", nil];
for (NSString *imagePath in mainDishImages) {
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newRecipe = [NSEntityDescription insertNewObjectForEntityForName:#"Recipe" inManagedObjectContext:context];
[newRecipe setValue:imagePath forKey:#"imageFilePath"];
}
for (NSString *imagePath in drinkDessertImages) {
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newRecipe = [NSEntityDescription insertNewObjectForEntityForName:#"Deserts" inManagedObjectContext:context];
[newRecipe setValue:imagePath forKey:#"imageFilePath"];
}
}
And I access that data in my collectionViewController, I access that data.
- (NSManagedObjectContext *)managedObjectContext{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Deserts"];
deserts = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSFetchRequest *fetchRequestTwo = [[NSFetchRequest alloc] initWithEntityName:#"Recipe"];
meals = [[managedObjectContext executeFetchRequest:fetchRequestTwo error:nil] mutableCopy];
recipeImages = [NSArray arrayWithObjects:meals, deserts, nil];
[self.collectionView reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Deserts"];
deserts = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSFetchRequest *fetchRequestTwo = [[NSFetchRequest alloc] initWithEntityName:#"Recipe"];
meals = [[managedObjectContext executeFetchRequest:fetchRequestTwo error:nil] mutableCopy];
recipeImages = [NSArray arrayWithObjects:meals, deserts, nil];
UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
collectionViewLayout.sectionInset = UIEdgeInsetsMake(5, 0, 5, 0);
self.navigationController.navigationBar.translucent = YES;
self.collectionView.contentInset = (UIEdgeInsetsMake(44, 0, 0, 0));
selectedRecipes = [NSMutableArray array];
}
According to crashalytics, the error is in the line where it says
recipeImageView.image = [UIImage imageNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];
In the method
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame"]];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame-selected.png"]];
return cell;
}
I hope you can help. Thanks In Advance!
The UIImage method imageNamed takes an NSString as argument, but you pass a NSManagedObject to it.
You should get the image path from the managed object first. Try this:
id managedObject = [recipeImages[indexPath.section] objectAtIndex:indexPath.row];
NSString* imagePath = [managedObject valueForKey:#"imageFilePath"];
recipeImageView.image = [UIImage imageNamed:imagePath];

how could i integrate via me social site into iphone app

hi i want to integrate Via Me social site into my iphone app,i googled but didn't find any samples.
The basic process is as follows:
Create a custom URL scheme for your app. Via Me will use this after the user has been authenticated, to return to your app. In my example, I created one called "robviame://"
Register your app at http://via.me/developers. This will give you a client id and a client secret:
When you want to authenticate the user, you call:
NSString *redirectUri = [[self redirectURI] stringByAddingPercentEscapesForURLParameterUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:#"https://api.via.me/oauth/authorize/?client_id=%#&redirect_uri=%#&response_type=code", kClientID, redirectUri];
NSURL *url = [NSURL URLWithString:urlString];
[[UIApplication sharedApplication] openURL:url];
What that will do is fire up your web browser and give the user a chance to log on and grant permissions to your app. When user finishes that process, because you've defined your custom URL scheme, it will call the following method in your app delegate:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
// do whatever you want here to parse the code provided back to the app
}
for example, I'll call a handler for my Via Me response:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
ViaMeManager *viaMeManager = [ViaMeManager sharedManager];
if ([[url host] isEqualToString:viaMeManager.host])
{
[viaMeManager handleViaMeResponse:[self parseQueryString:[url query]]];
return YES;
}
return NO;
}
// convert the query string into a dictionary
- (NSDictionary *)parseQueryString:(NSString *)query
{
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSArray *queryParameters = [query componentsSeparatedByString:#"&"];
for (NSString *queryParameter in queryParameters) {
NSArray *elements = [queryParameter componentsSeparatedByString:#"="];
NSString *key = [elements[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *value = [elements[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
value = [[value componentsSeparatedByString:#"+"] componentsJoinedByString:#" "];
[dictionary setObject:value forKey:key];
}
return dictionary;
}
That handler might, for example, save the code and then request the access token:
- (void)handleViaMeResponse:(NSDictionary *)parameters
{
self.code = parameters[#"code"];
if (self.code)
{
// save the code
[[NSUserDefaults standardUserDefaults] setValue:self.code forKey:kViaMeUserDefaultKeyCode];
[[NSUserDefaults standardUserDefaults] synchronize];
// now let's authenticate the user and get an access key
[self requestToken];
}
else
{
NSLog(#"%s: parameters = %#", __FUNCTION__, parameters);
NSString *errorCode = parameters[#"error"];
if ([errorCode isEqualToString:#"access_denied"])
{
[[[UIAlertView alloc] initWithTitle:nil
message:#"Via Me functions will not be enabled because you did not authorize this app"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
else
{
[[[UIAlertView alloc] initWithTitle:nil
message:#"Unknown Via Me authorization error"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
}
}
and the code to retrieve the token might look like:
- (void)requestToken
{
NSURL *url = [NSURL URLWithString:#"https://api.via.me/oauth/access_token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSDictionary *paramsDictionary = #{#"client_id" : kClientID,
#"client_secret" : kClientSecret,
#"grant_type" : #"authorization_code",
#"redirect_uri" : [self redirectURI],
#"code" : self.code,
#"response_type" : #"token"
};
NSMutableArray *paramsArray = [NSMutableArray array];
[paramsDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
[paramsArray addObject:[NSString stringWithFormat:#"%#=%#", key, [obj stringByAddingPercentEscapesForURLParameterUsingEncoding:NSUTF8StringEncoding]]];
}];
NSData *paramsData = [[paramsArray componentsJoinedByString:#"&"] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:paramsData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error)
{
NSLog(#"%s: NSURLConnection error = %#", __FUNCTION__, error);
return;
}
NSError *parseError;
id results = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (parseError)
{
NSLog(#"%s: NSJSONSerialization error = %#", __FUNCTION__, parseError);
return;
}
self.accessToken = results[#"access_token"];
if (self.accessToken)
{
[[NSUserDefaults standardUserDefaults] setValue:self.accessToken forKey:kViaMeUserDefaultKeyAccessToken];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
}
Hopefully this will be enough to get you going. This is described in greater detail at the http://via.me/developers page.

Calling an API with UISearchBar

I have a UITableView that displays results from an API. The API is called whenever the user types into the UISearchBar via searchBar:textDidChange:. Effectively implementing an autocomplete search. My problem is the results loaded into the UITableView seem to be an iteration behind the last API call.
Example:
User types "union" into the UISearchBar, however no results are shown in the UITableView. User types any character after "union", "unions" for example, and the API results from "union" are displayed in the UITableView. When user scrolls down through results (of "unions", but really "union") "repopulated cells" display "unions" result.
SearchViewController.h
#import <UIKit/UIKit.h>
#interface SearchViewController : UIViewController <UITextFieldDelegate, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, UISearchDisplayDelegate>{
UITableView *searchTableView;
UISearchBar *sBar;
UISearchDisplayController *searchDisplayController;
}
#property (strong, nonatomic) NSArray *loadedSearches;
#end
SearchViewController.m
#import "SearchViewController.h"
#import "AFJSONRequestOperation.h"
#interface SearchViewController ()
#end
#implementation SearchViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = #"Search";
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
searchTableView = [[UITableView alloc] initWithFrame:self.view.bounds];
searchTableView.delegate = self;
searchTableView.dataSource = self;
[self.view addSubview:searchTableView];
sBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 160, 44)];
sBar.placeholder = #"Bus Route to...";
sBar.delegate = self;
searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:sBar contentsController:self];
searchDisplayController.delegate = self;
searchDisplayController.searchResultsDataSource = searchTableView.dataSource;
searchDisplayController.searchResultsDelegate = searchTableView.delegate;
searchTableView.tableHeaderView = sBar;
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSString *searchQuery = [NSString stringWithFormat:#"https://api.foursquare.com/v2/venues/search?ll=40.4263,-86.9177&client_id=xxx&client_secret=yyy&v=20121223&query='%#'",searchText];
searchQuery = [searchQuery stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:searchQuery];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){
self.loadedSearches = JSON[#"response"][#"venues"];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
NSLog(#"%#", error.localizedDescription);
}];
[operation start];
[searchTableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.loadedSearches.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
cell.textLabel.text = self.loadedSearches[indexPath.row][#"name"];
return cell;
}
#end
If my problem isn't clear, let me know.
Feel free to critique other aspects of the code, however I really would appreciate the solution to my problem:) Thanks in advance.
Example API response - http://pastebin.com/UZ1H2Zwy
The problem seems to be that you are refreshing the table before you get the data as you are making an asynchronous operation with AFJSONRequestOperation. So your model is probably getting updated correctly but your tableview is one refresh behind. Try moving [searchTableView reloadData] inside the block success callback:
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
self.loadedSearches = JSON[#"response"][#"venues"];
// refreshing the TableView when the block gets the response
[searchTableView reloadData];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
{
NSLog(#"%#", error.localizedDescription);
}];
Hope this works.
Your requests work asynchronously, it is not probably related with scroll or something. Just result returns at that time. Try to cancel the previous requests. For example if you try to search "unions" then cancel the "union" request. Hope it helps.

TWRequest from a dictionary in a tableView Cell

I am trying to propagate a table view with a custom cell with the results of a TWRequest with no luck. I am trying to store the tweets in a dictionary object then calling an ObjectAtKey request and putting into a string. Here is my code - any help would be appreciated. Thanks -
-(void)fetchTweets
{
// Do a simple search, using the Twitter API
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
#"http://search.twitter.com/search.json?q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"]
parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(#"Twitter response: %#", dict);
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSString *tweetText = [dict objectForKey:#"text"];
NSArray *tweetComponents = [tweetText componentsSeparatedByString:#":"];
cell.Header.text = [tweetComponents objectAtIndex:0];
cell.Details.text = [tweetComponents objectAtIndex:1];
cell.Date.text = [tweetComponents objectAtIndex:2];
return cell;
}
You will need to create an NSMutableArray of the tweets from the Twitter response.
Each tweet being a separate object.
NSMutableArray *resultArray = [[NSMutableArray] alloc] init];
for (NSDictionary *tweet in dict)
{
[resultArray addObject:tweet];
}
Then in cellForRowAtIndexPath retrieve the object based on the row of the table, something like
TweetResult *tweetResult [resultArray objectAtIndex:[indexPath row]];

Resources