How to integrate NSUrlsession in ios - ios

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());
}
}];

Related

EXC_BAD_ACCESS NSLog(#"Error decoding JSON data : %#", error.localizedDescription); on OpenWeather API

I am trying to use a location-based Weather app and it is crashing as soon as I open the view for that page.
This is the method;
- (WeatherModel *) parseWeatherData: (NSData *) data {
WeatherModel *weatherModel = [[WeatherModel alloc] init];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingAllowFragments error: &error];
if (error) {
NSLog(#"Error decoding JSON data : %#", error.localizedDescription);
[self->_delegate didFailedWithError: error];
return nil;
}
if ([jsonObject isKindOfClass: [NSDictionary class]]) {
NSMutableDictionary *dicJsonObject = [[NSMutableDictionary alloc] initWithDictionary: jsonObject];
NSString *cityName = [dicJsonObject valueForKey: #"name"];
double temperature = [[[dicJsonObject valueForKey: #"main"] valueForKey: #"temp"] doubleValue];
NSMutableArray *arrWeatherData = [[NSMutableArray alloc] initWithArray: [dicJsonObject valueForKey: #"weather"]];
weatherModel.strCityName = cityName;
weatherModel.temperature = temperature;
weatherModel.weatherConditionID = [[[arrWeatherData objectAtIndex: 0] valueForKey: #"id"] intValue];
}
return weatherModel;
}
It is crashing on this line;
if (error) {
NSLog(#"Error decoding JSON data : %#", error.localizedDescription);
[self->_delegate didFailedWithError: error];
return nil;
}
If I comment out the NSLog section and [self->_delegate didFailedWithError: error];
the app does not crash, but then does not function as expected either...
The second part of the crash using debug is here;
- (void) fetchWeatherForCity: (NSString *) cityName {
_strWeatherURL = [NSString stringWithFormat: #"https://api.openweathermap.org/data/2.5/weather?q=%#&appid=bfea07812845ff9cb7e", cityName];
NSURL *weatherURL = [[NSURL alloc] initWithString: _strWeatherURL];
NSURLSessionConfiguration *urlSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration: urlSessionConfiguration];
NSURLSessionDataTask *task = [urlSession dataTaskWithURL: weatherURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(#"Error fetching weather data : %#", error);
[self->_delegate didFailedWithError: error];
return;
}
WeatherModel *weatherModel = [[WeatherModel alloc] init];
weatherModel = [self parseWeatherData: data];
if (weatherModel != nil) {
[self->_delegate didUpdateWeather: weatherModel];
}
}];
[task resume];
}
On this line;
weatherModel = [self parseWeatherData: data];

Encode NSDictionary to send across AFNetworking

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

afnetworking in singletone and waiting requests from another controller (objective c)

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) {
}];

shouldPerformSegueWithIdentifier issue

I tried too much to solve my bellow issue but i am failed.Please help me to solve this issue. I have login view and after validating id and password i am pushing it to next view controller.Please check bellow image.
Issue - When Id and Password is correct it's pushing to next view controller but after 2 clicks on login button.
Code -
ServiceManager.m
-(void)initGetAppServiceRequestWithUrl:(NSString *)baseUrl onCompletion:
(ServiceCompletionHandler)handler
{
NSString *fullUrl = [NSString stringWithFormat:#"%#",[baseUrl
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:fullUrl]];
[NSURLConnection sendAsynchronousRequest:(NSURLRequest *)request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,NSData *data,NSError *error)
{
if (error) {
handler(nil,error);
// NSLog(#"error = %#",error);
}
else
{ handler(data, nil);
// NSLog(#"data = %#",data);
}
}];
}
JSONResponseHandler.m
+(void)handleResponseData:(NSData *)responseData onCompletion:(JSONHandler)handler
{
if (responseData) {
NSError *jsonParseError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:&jsonParseError];
if (!json) {
handler(nil , jsonParseError);
}
else
{
handler (json , nil);
}
}
}
ASKevrServiceManager.m
-(void)login:(Login *)login completionHandler:(ServiceCompletionHandler)handler
{
NSString *loginUrl = [NSString
stringWithFormat:#"http://249development.us/johnsan/askever/login.php?
login=%#&password=%#",login.emailAddr , login.password];
[self initGetAppServiceRequestWithUrl:loginUrl onCompletion:^(id object, NSError
*error)
{
handler(object , error);
}
];
}
ASKevrOperationManager.m
+(void)login:(Login *)login handler:(OperationHandler)handler
{
ASKevrServiceManager *serviceManager = [[ASKevrServiceManager alloc]init];
[serviceManager login:login completionHandler:^(id object, NSError *error)
{
[JSONResponseHandler handleResponseData:object onCompletion:^(NSDictionary
*json , NSError *jsonError)
{
if(json)
{
handler(json , nil , YES);
}
else
{
handler(nil , jsonError , NO);
}
}];
}];
}
LoginViewController.m
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
if ([identifier isEqualToString:#"pushTab"])
{
if ([emailTxt.text isEqualToString:#""] || [passwordTxt.text
isEqualToString:#""])
{
[self showAlertWithMessage:#"Please write your id or password"];
return NO;
}
else
{
Login *loginModel = [[Login alloc]init];
loginModel.emailAddr =emailTxt.text;
loginModel.password = passwordTxt.text;
[ASKevrOperationManager login:loginModel handler:^(id object , NSError *error ,
BOOL success)
{
if (success)
{
NSLog(#"object =%#",object);
NSDictionary *arr = [object objectForKey:#"response"];
str = [arr objectForKey:#"flag"];
//check for error
NSDictionary *toDict = [object objectForKey:#"response"];
currentUserId = [toDict objectForKey:#"c_id"];
NSLog(#"currentUserId = %#",currentUserId);
}
else
{
[self showAlertWithMessage:#"Wrong Id or Password."];
}
}];
NSLog(#"str = %#",str);
if ([str isEqualToString:#"1"])
{
// [self showAlertWithMessage:#"Wrong Id or Password."];
return YES;
}
}
}
return NO;
}
When pressing login button do run the code
if (![emailTxt.text isEqualToString:#""] &&
![passwordTxt.text isEqualToString:#""]){
Login *loginModel = [[Login alloc]init];
loginModel.emailAddr =emailTxt.text;
loginModel.password = passwordTxt.text;
[ASKevrOperationManager login:loginModel handler:^(id object , NSError *error ,
BOOL success)
{
if (success){
NSLog(#"object =%#",object);
NSDictionary *arr = [object objectForKey:#"response"];
str = [arr objectForKey:#"flag"];
//check for error
NSDictionary *toDict = [object objectForKey:#"response"];
currentUserId = [toDict objectForKey:#"c_id"];
NSLog(#"currentUserId = %#",currentUserId);
//perform the segue only when succesful
[self performSegueWithIdentifier:#"yourSegue" sender:sender];
}else{
[self showAlertWithMessage:#"Wrong Id or Password."];
}
}];
}else {
[self showAlertWithMessage:#"Please write your id or password"];
}
Keep your shouldPerformSegueWithIdentifier simple
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
if ([identifier isEqualToString:#"pushTab"])
{
//don't put logic here
//put code here only if you need to pass data
//to the next screen
return YES:
}
return NO;
}

How to add new data to a TableView in addition to the previous data that it already contains?

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.

Resources