I am writing an Apple iPhone application.
A have got a class - singleton which sending a requests to the server (ServerManager) and a ViewController which using methods of singletone and another methods (analyzing requests for example).
How to perform queries from singletone in viewcontroller on the line? One after the other? Not parallel?
//for example authoriztion in Twitter
//here my query for the Twitter Server
- (void) getTweetsFromTW:(NSInteger) count
onSuccess:(void(^)(NSArray* news)) success
onFailure:(void(^)(NSError* error, NSInteger statusCode)) failure {
//NSString* countStr = [NSString stringWithFormat:#"%ld", count];
NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:#"ld", count], #"count", nil];
NSError* requestError = [[NSError alloc] init];
NSURLRequest* myRequest = [[[Twitter sharedInstance] APIClient]
URLRequestWithMethod:#"GET"
URL:#"https://api.twitter.com/1.1/statuses/home_timeline.json"
parameters:params
error:&requestError];
[[[Twitter sharedInstance] APIClient]
sendTwitterRequest:myRequest
completion:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data) {
NSError* jsonError;
NSArray* jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
//NSLog(#"%#", jsonArray); //вывод ответа сервера
NSMutableArray* textsArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [jsonArray count]; i++) {
NSArray* test = [[NSArray alloc] initWithObjects:[jsonArray objectAtIndex:i], nil];
NSDictionary* dict = [NSDictionary dictionaryWithObjects:test
forKeys:[test valueForKey:#"intField"]];
NSDictionary* dictionary = dict[[[dict allKeys] objectAtIndex:0]];
//NSLog(#"%#", [dictionary objectForKey:#"text"]); //вывод текстов твитов
[textsArray addObject:[dictionary objectForKey:#"text"]];
}
if (success) {
success(textsArray);
}
}
}];
}
//here is my viewcontroller
[[ServerManager sharedManager] getTweetsFromTW:10
onSuccess:^(NSArray *news) {
for (int i = 0; i < [news count]; i++) {
NSLog(#"%#", [news objectAtIndex:i]);
}
[_textsFromTW addObjectsFromArray:news];
}
onFailure:^(NSError *error, NSInteger statusCode) {
}];
//I need send this requests in a line not parallel
[[ServerManager sharedManager] getNewsFromVK:300
filter:#"post"
onSuccess:^(NSArray *news) {
for (int i = 0; i < [news count]; i++) {
NSLog(#"%#", [[news objectAtIndex:i] objectForKey:#"text"]);
if ([[news objectAtIndex:i] objectForKey:#"text"] != nil) {
[_textsFromVK addObject:[[news objectAtIndex:i] objectForKey:#"text"]];
}
}
}
onFailure:^(NSError *error, NSInteger statusCode) {
}];
Related
Hi I am very new to ios and in my app I am using NSUrlSession for integrating services.
Here my main problem is when I get a response from the server, I can't handle them properly.
When I get a correct response, then see the below json stucture:-
responseObject = {
{
Name = Broad;
DeptNo = A00;
BatchNo = 23;
DeptId = 120;
},
{
Name = James;
DeptNo = B00;
BatchNo = 23;
DeptId = 123;
},
}
when I get a wrong response, see the below json stucture:-
responseObject = {
error = 1;
message = "Invalid Code";
}
when I get a correct response from the server, I am getting an exception in my below if block(like __NSCFArray objectForKey:]: unrecognized selector sent to instance 0x1611c200') and when I get a wrong response then T get exception in my else block
Please help me how to handle them
my code:-
(void) GetCallService1: (id)MainResponse{
dispatch_async(dispatch_get_main_queue(), ^{
NameArray = [[NSMutableArray alloc]init];
IdArray = [[NSMutableArray alloc]init];
if([MainResponse objectForKey:#"error"] != nil)
{
NSLog(#"No data available");
}
else{
for (NSDictionary *obj in MainResponse) {
if([obj objectForKey:#"Name"] && [obj objectForKey:#"DeptNo"]) {
NSString * Name = [obj objectForKey:#"Name"];
[NameArray addObject:Name];
NSString * Id = [obj objectForKey:#"id"];
[IdArray addObject:Id];
}
}
}
});
}
1)Change Your implementation like below
2)I checked is it dictionary type & error key has some value
3)Earlier you were calling objectForKey on Array, therefore it was crashing
-(void) GetCallService1: (id)MainResponse{
dispatch_async(dispatch_get_main_queue(), ^{
NameArray = [[NSMutableArray alloc]init];
IdArray = [[NSMutableArray alloc]init];
//here I checked is it dictionary type & error key has some value
if ([MainResponse isKindOfClass:[NSDictionary class ]] &&[MainResponse objectForKey:#"error"])
{
NSLog(#"No data available");
}
else{
for (NSDictionary *obj in MainResponse) {
if([obj objectForKey:#"Name"] && [obj objectForKey:#"DeptNo"]) {
NSString * Name = [obj objectForKey:#"Name"];
[NameArray addObject:Name];
NSString * Id = [obj objectForKey:#"id"];
[IdArray addObject:Id];
}
}
}
});
}
Try this:
//Result Block
typedef void (^ResultBlock)(id, NSError*);
//URL request
-(void)requestURL:(NSURLRequest *)request withResult:(ResultBlock)resultHandler{
//URLSession
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
if(!error){
NSError *jsonError = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if([result isKindOfClass:[NSArray class]]){
//Success
resultHandler(result,nil);
}
else if([result isKindOfClass:[NSDictionary class]]){
if([[result objectForKey:#"error"] integerValue]){
//Failure.
NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
[errorDetail setValue:[result objectForKey:#"message"] forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:#"Error" code:100 userInfo:errorDetail];
resultHandler(nil, errorDetail);
}
}
}
}];
[task resume];
}
//Call your requestURL method:
[self requestURL:request withResult:^(id result, NSError *error){
if(!error){
//Success, Read & update your list
}
else{
//Error
// NSLog(error.localizedDescription());
}
}];
How can i URLEncode a NSDictionary so i can send it across AFNetworking.
The code is as follows:
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
How can i Encode this NSDictionary so i can send it across AFNetworking ?
Depends how you wish to send your data:
1) #"application/json" in which case you would use [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]
2) #"application/x-www-form-urlencoded" in which case you basically want to create the string: ?id=1211&man=33 from your dictionary rus.
Here's some code, may not be the most efficient by you get the idea:
NSString *temp;
int i=0;
for(NSString *key in options.params.allKeys)
{
NSString *value = [options.params objectForKey:key];
[parameters setObject:value forKey:key];
if(i==0)
{
temp = [NSString stringWithFormat:#"?%#=%#", key,value];
}
else
{
temp = [NSString stringWithFormat:#"%#&%#=%#", temp, key, value];
}
}
Note: may or may not be relevant to you, but my two cents:
I use AFHTTPSessionManager which handles all the details for me including url encoding, so I just pass in the desired dictionary:
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
[self POST:#"/api/place/nearbysearch" parameters:rus success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"nearbyPlaces: success");
[self fetchedPlacesData:responseObject block:block];
if(task != nil && task.originalRequest != nil)
{
NSString *url = [task.originalRequest.URL absoluteString];
[self saveNearbySearchEvent:url params:params];
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"nearbyPlaces: error: %#", error);
block(self, nil, error);
}];
AFHTTPSessionManager encapsulates a lot of functionality included serializing the data: AFURLRequestSerialization either as JSON or HTTP Request. In case you interested on what AFHTTPSessionManager actually does here's some detail:
A) HTTP Request
Here's the code from AFURLRequestSerialization.m:
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
NSString *query = nil;
if (self.queryStringSerialization) {
NSError *serializationError;
query = self.queryStringSerialization(request, parameters, &serializationError);
if (serializationError) {
if (error) {
*error = serializationError;
}
return nil;
}
} else {
switch (self.queryStringSerializationStyle) {
case AFHTTPRequestQueryStringDefaultStyle:
query = AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding);
break;
}
}
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? #"&%#" : #"?%#", query]];
} else {
if (![mutableRequest valueForHTTPHeaderField:#"Content-Type"]) {
[mutableRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
}
[mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
}
}
return mutableRequest;
}
B) JSON
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
return [super requestBySerializingRequest:request withParameters:parameters error:error];
}
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
if (![mutableRequest valueForHTTPHeaderField:#"Content-Type"]) {
[mutableRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
}
[mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
}
return mutableRequest;
}
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
If you are exchanging JSON data with your server:
NSError *error = nil;
NSData *aRequestData = [NSJSONSerialization dataWithJSONObject:rus options:NSJSONWritingPrettyPrinted error:&error];
if (!error) {
[urlRequest setHTTPBody:aRequestData];
}
If you are exchanging PLIST data with your server:
[self stringByAppendingQueryParameters:rus appendQuestionMark:NO];
- (NSString *)stringByAppendingQueryParameters:(NSDictionary *)iParameters appendQuestionMark:(BOOL)iAppendQuestionMark {
BOOL aAppendAmpersand = YES;
NSMutableString *aWorking = [NSMutableString stringWithString:self];
if (iAppendQuestionMark) {
NSRange aQueryBeginning = [self rangeOfString:#"?"];
if (aQueryBeginning.location == NSNotFound) {
[aWorking appendString:#"?"];
aAppendAmpersand = NO;
}
} else {
aAppendAmpersand = NO;
}
for (id aKey in iParameters) {
id aValue = [iParameters valueForKey:aKey];
NSString *aKeyStr = [self convertObjectToURLEncodedValue:aKey];
if (aAppendAmpersand) {
[aWorking appendString:#"&"];
} else {
aAppendAmpersand = YES;
}
if ([aValue isKindOfClass:[NSArray class]]) {
NSArray *aSubParamaters = (NSArray *)aValue;
BOOL aFirstTime = YES;
for (id aSubValue in aSubParamaters) {
NSString *aValueString = [self convertObjectToURLEncodedValue:aSubValue];
if (!aFirstTime) {
[aWorking appendString:#"&"];
}
[aWorking appendString:aKeyStr];
[aWorking appendString:#"="];
[aWorking appendString:aValueString];
aFirstTime = NO;
}
} else {
NSString *aValueString = [self convertObjectToURLEncodedValue:aValue];
[aWorking appendString:aKeyStr];
[aWorking appendString:#"="];
[aWorking appendString:aValueString];
}
}
return [NSString stringWithString:aWorking];
}
- (NSString *)convertObjectToURLEncodedValue:(id)iObject {
NSString *anIntermediate = nil;
if ([iObject isKindOfClass:[NSString class]]) {
anIntermediate = iObject;
} else if ([iObject respondsToSelector:#selector(stringValue)]) {
anIntermediate = [iObject stringValue];
} else {
anIntermediate = [iObject description];
}
NSString *anEncodingString = (__bridge_transfer NSString *)(CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef)anIntermediate,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 ));
return anEncodingString;
}
May be my question looks strange, but... (hope somebody help me)
There are two methods in which I load some data from FTP. Sometimes application hung on these methods.
Checking internet connection.
If internet avail:
#interface Download : NSObject {
NSOperationQueue *operationQueue;
}
...
if (!operationQueue) {
operationQueue = [NSOperationQueue new];
}
NSInvocationOperation *operation1;
operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(loadIngredientsFromJSON) object:nil];
[operationQueue addOperation:operation1];
NSInvocationOperation *operation2;
operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(loadRecipesFromJSON) object:nil];
[operation2 addDependency:operation1];
[operationQueue addOperation:operation2];
[operationQueue addObserver:self forKeyPath:#"operations" options:0 context:NULL];
Methods loadIngredientsFromJSON & loadRecipesFromJSON
-(void) loadIngredientsFromJSON
{
NSInteger countInBase = [self dataCountInEntity:#"Ingredients"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"ftp://...Ingredients.json"]];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *error = nil;
if (!responseData) {
return;
}
NSDictionary *ingredientsDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (!ingredientsDictionary) {
return;
}
//NSLog(#"%#", [ingredientsDictionary description]);
NSArray *keys = [ingredientsDictionary allKeys];
if (!countInBase && [ingredientsDictionary count]>0) {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
for (int i=0; i<[ingredientsDictionary count]; i++) {
id aKey = [keys objectAtIndex:i];
NSArray *ingrData = [ingredientsDictionary objectForKey:[NSString stringWithFormat:#"%#", aKey]];
NSArray *tmpArray = [NSArray arrayWithObjects:aKey, [ingrData objectAtIndex:0], [ingrData objectAtIndex:1], nil];
Ingredients *ingredient = [NSEntityDescription insertNewObjectForEntityForName:#"Ingredients" inManagedObjectContext:appDelegate.managedObjectContext];
ingredient.code = [NSNumber numberWithInteger:[[tmpArray objectAtIndex:0] integerValue]];
ingredient.name = [tmpArray objectAtIndex:1];
ingredient.units = [tmpArray objectAtIndex:2];
ingredient.type = [NSNumber numberWithInt:1];
[appDelegate.managedObjectContext save:nil];
}
}
}
...
- (void) loadRecipesFromJSON
{
NSInteger missedCount = 0;
NSInteger recipeCode = 0;
NSString *recipesPath = #"ftp://...";
do {
recipeCode ++;
NSString *recipeFileName = [NSString stringWithFormat:#"recipes/%05d.json", recipeCode];
NSString *recipeFileFullPath = [recipesPath stringByAppendingString:recipeFileName];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:recipeFileFullPath]];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *error = nil;
if (!responseData) {
missedCount ++;
continue;
}
NSDictionary *recipeDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (!recipeDictionary) {
missedCount ++;
continue;
}
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSInteger recipeCount = [self isDataExistInEntity:#"Recipes" withCode:[[recipeDictionary objectForKey:#"recipeCode"] integerValue]];
if (recipeCount == 0) {
Recipes *recipe = [NSEntityDescription insertNewObjectForEntityForName:#"Recipes" inManagedObjectContext:appDelegate.managedObjectContext];
recipe.code = [recipeDictionary objectForKey:#"recipeCode"];
recipe.dateUpdated = [recipeDictionary objectForKey:#"dateEdited"];
recipe.inCategory = [recipeDictionary objectForKey:#"inCategory"];
recipe.name = [recipeDictionary objectForKey:#"recipe"];
recipe.difficulty = [recipeDictionary objectForKey:#"difficulty"];
recipe.personCount = [recipeDictionary objectForKey:#"personCount"];
recipe.prepHour = [recipeDictionary objectForKey:#"prepHour"];
recipe.prepMin = [recipeDictionary objectForKey:#"prepMin"];
int seconds = ([recipe.prepMin intValue]*60)+([recipe.prepHour intValue] * 60 * 60);
recipe.prepTime = [NSNumber numberWithInt: seconds];
recipe.isPaid = [recipeDictionary objectForKey:#"isPaid"];
recipe.comment = [recipeDictionary objectForKey:#"comments"];
NSDictionary *ingredients = [recipeDictionary objectForKey:#"ingredients"];
NSArray *keys = [ingredients allKeys];
if ([keys count] > 0) {
for (int i=0; i<[keys count]; i++) {
Join *join = [NSEntityDescription insertNewObjectForEntityForName:#"Join" inManagedObjectContext:appDelegate.managedObjectContext];
join.recipeCode = [recipeDictionary objectForKey:#"recipeCode"];
id aKey = [keys objectAtIndex:i];
join.ingredientCode = [NSNumber numberWithInteger:[aKey integerValue]];
NSString *str = [ingredients objectForKey:aKey];
double num = [str doubleValue];
join.count = [NSNumber numberWithDouble:num];
join.inCart = [NSNumber numberWithInt:0];
}
}
NSDictionary *prepStages = [recipeDictionary objectForKey:#"prepStage"];
keys = [prepStages allKeys];
if ([keys count] > 0) {
for (int i=0; i<[keys count]; i++) {
PrepStages *prepStage = [NSEntityDescription insertNewObjectForEntityForName:#"PrepStages" inManagedObjectContext:appDelegate.managedObjectContext];
prepStage.recipeCode = [recipeDictionary objectForKey:#"recipeCode"];
id aKey = [keys objectAtIndex:i];
prepStage.order = [NSNumber numberWithInteger:[aKey integerValue]];
prepStage.descriptions = [prepStages objectForKey:aKey];
//загрузка картинки
NSString *recipeImageName = [NSString stringWithFormat:#"recipeImages/%05d-%#.jpg", recipeCode, [NSNumber numberWithInteger:[aKey integerValue]]];
NSString *recipeImageFullPath = [recipesPath stringByAppendingString:recipeImageName];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:recipeImageFullPath]];
if (request) {
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if (responseData) {
UIImage *image = [UIImage imageWithData:responseData];
prepStage.image = image;
}
}
}
}
[appDelegate.managedObjectContext save:nil];
}
else {
missedCount ++;
continue;
}
} while (missedCount < 10);
}
Sometimes in one of these two methods application hung and control freeze.
Can anybody give me some advice in which line there may be the bug.
I confused...
EDITED
I noticed interesting thing:
Download process starts when app run. It downloads Recipes from server and inserts them to CoreData. If I tap to see recipe list I use appDelegate.managedObjectContext to fetch data. Download also uses appDelegate.managedObjectContext when it want to insert data.
Can this contain problem?
I'm developing an iOS app that includes a facebook feed of a users wall. Using the graph api with the following URL:
feedURL = [NSString stringWithFormat:#"https://graph.facebook.com/%#/feed?
access_token=%#&since=%#&until=%#",kFaceBookID,FBSession.activeSession.accessToken,
[dateRange objectForKey:#"since"], [dateRange objectForKey:#"until"]];
I get back data that only one result and a dictionary entry for paging. When I do a NSURLRequest with the "next" URL I get back 0 results. If I cut and paste that same URL into a web browser I get back 25 results. Any ideas on why?
Here is the code I am using:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *nextPageURL;
NSError *jsonError;
if (!jsonError) {
NSDictionary *rDict = [NSJSONSerialization JSONObjectWithData:_postData
options:0
error:&jsonError];
nextPageURL = [[rDict objectForKey:#"paging"]objectForKey:#"next"];
NSArray *rArray = [rDict objectForKey:#"data"];
DLog(#"Posts Dictionary = %#\n\n",rDict);
for (NSDictionary *rPost in rArray) {
FBPost *post = [[FBPost alloc]initFBPostWithDictionary:rPost];
[feedsArray addObject:post];
}
}
else
{
ALog(#"json error = %#",[jsonError localizedDescription]);
[activity stopAnimating];
NSString *errorMessage = [NSString stringWithFormat:#"Facebook status request failed with error: %#\nCheck your network connection and try again later",[jsonError localizedDescription]];
[self quit:errorMessage];
}
[feedsTable reloadData];
if (nextPageURL && [feedsArray count] < 30) {
DLog(#"Next Feed URL = %#",nextPageURL);
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:nextPageURL]];
if (![[NSURLConnection alloc] initWithRequest:request delegate:self]) {
ALog(#"Connection failed for request: %#",request);
}
}
}
I am answering my own question as I took another look at the entire logic and completely changed my approach to use [FBRequestConnection...] instead. Here is the code if anyone is interested. Note that I fetch one weeks worth of feed messages at a time to improve the tableview performance.
- (void) fetchFBFeedsForDateRange:(NSDictionary *)dateRange;
{
_postData = [[NSMutableData alloc]init];
//since, until is a decremented one week at a time date range.
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[dateRange objectForKey:#"since"], #"since",
[dateRange objectForKey:#"until"], #"until",
nil];
NSString *gPath = [NSString stringWithFormat:#"%#/feed",kFaceBookID];
[FBRequestConnection startWithGraphPath:gPath
parameters:params
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSArray *rArray = [result objectForKey:#"data"];
//DLog(#"Posts Array = %#\n\n",rArray);
for (NSDictionary *rPost in rArray) {
FBPost *post = [[FBPost alloc]initFBPostWithDictionary:rPost];
if (post.type) {
if (!post.skip) {
[feedsArray addObject:post];
}
}
}
[feedsTable reloadData];
if ([feedsArray count] < kFaceBookMaxPostsToDisplay) {
[self performSelector:#selector(fetchPreviousWeek)];
}
else
{
[activity stopAnimating];
}
}
else
{
[activity stopAnimating];
NSString *errorMessage = [NSString stringWithFormat:#"Facebook status request failed with error: %#\nCheck your network connection and try again later",[error localizedDescription]];
[self quit:errorMessage];
}
}];
}
I am working with my Twitter app. I am fetching the search result in a TableView. When I am refreshing the search results, the table gets populated with the new incoming tweets and the earlier one goes out. Can any one suggest me a way to just add new tweets along with the earlier tweets?
//my array
-(NSMutableArray *)retrievedTweets
{
if (retrievedTweets == nil)
{
retrievedTweets = [NSMutableArray arrayWithCapacity:50];
}
return retrievedTweets;
}
-(BOOL)checkCanTweet
{
if ([TWTweetComposeViewController canSendTweet])
{
self.goButton.enabled = YES;
self.goButton.alpha = 1.0;
return YES;
}
else
{
self.goButton.enabled = NO;
self.goButton.alpha = 0.6;
return NO;
}
}
//search function
-(void)searchTweet{
if (retrievedTweets == nil) {
retrievedTweets=[[NSMutableArray alloc] init];
}
//retrievedTweets = nil;
if ([self checkCanTweet])
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType =
[accountStore
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter ];
[accountStore requestAccessToAccountsWithType:accountType
withCompletionHandler:^(BOOL granted, NSError *error)
{
if (granted)
{
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
if ([accountsArray count] >0)
{
[self.retrievedTweets removeAllObjects];
NSString *str1 = [[NSString alloc]initWithFormat:#"http://search.twitter.com/search.json?q="];
//NSString *str2 = [[NSString alloc]initWithFormat:#"http://search.twitter.com/search.json?q=%23"];
NSString *textString = searchBarText.text;
NSString *urlString = [[NSString alloc]init];
if(textString==nil)
{
self.goButton.enabled = NO;
}
else {
self.goButton.enabled = YES;
unichar c = [textString characterAtIndex:0];
if(c == '#'){
NSString *newStr = [textString substringWithRange:NSMakeRange(1, [textString length]-1)];
urlString=[str1 stringByAppendingFormat:newStr];
}
else {
urlString = [str1 stringByAppendingFormat:searchBarText.text];
}
}
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:urlString] parameters:nil
requestMethod:TWRequestMethodGET];
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
NSError *jsonParsingError;
NSDictionary *homeTimeline = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError];
NSDictionary *results=[homeTimeline objectForKey:#"results"];
Search *current;
for (NSDictionary *dict in results)
{
current = [[Search alloc] initWithDictionary:dict];
[self.retrievedTweets addObject:current];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableViewPost reloadData];
});
}
else
{
NSLog(#"%#", [NSString stringWithFormat:#"HTTP response status: %i\n", [urlResponse statusCode]]);
}
// [self.tableViewPost reloadData];
}];
}
}
else
{
NSLog(#"Error, Twitter account access not granted.");
}
}];
}
[searchBarText resignFirstResponder];
}
You have not given the tableview delegates code.You need to addobject to the NSMutableArray everytime you retrieve the new data from web service.Before hitting the web service get the tableview's array(mutable) that you are using and add objects to it from the web service after parsing.Assign this array to the tableview array and then reload table.