Fetch Pagination URL Data with NSURLConnection in iOS - ios

i am newbie in iOS make an app that contain JSON Parsing data for that i use NSURLConnection and fetch data but here my URL Contain Pagination so, i want to fetch pagination data when tableView scroll for that i write a code like as
- (void)viewDidLoad
{
page=0;
NSString *path = [NSString stringWithFormat:#"http://isp.ebizzprojects.com/webservices/testimonial.php?page=%d",page];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
And Also I send second request when my table view scroll like as
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSInteger currentOffset = scrollView.contentOffset.y;
NSInteger maximumOffset = scrollView.contentSize.height- scrollView.frame.size.height;
if (maximumOffset - currentOffset <= 0)
{
page = page + 1;
[self getData];
}
}
-(void)getData
{
NSString *path = [NSString stringWithFormat:#"http://isp.ebizzprojects.com/webservices/testimonial.php?page=%d",page];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
And NSURLConnection delegate method like as
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[_parsedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_parsedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
_parsedData = nil;
_parsedData = [[NSMutableData alloc]init];
[[[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Connection Error" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil]show];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString =[[NSString alloc]initWithData:_parsedData encoding:NSUTF8StringEncoding];
NSDictionary *loDict = [responseString JSONValue];
self.responceArray=[loDict valueForKey:#"description"];
self.nameArray=[loDict valueForKey:#"name"];
self.testimonialTable.hidden=FALSE;
[self.testimonialTable reloadData];
}
From this my code when i scroll table view then i got only second page data i want to keep both data in to my table view when my tableview scroll please give me solution for this.
Thanks.

You need to add new items to array like, create NSMutableArray for self.responceArray and self.nameArray
[self.responceArray addObjectsFromArray:[loDict valueForKey:#"description"]];
[self.nameArray addObjectsFromArray:[loDict valueForKey:#"name"]];

Related

URL as a string and values in Xcode

I am working on a web service app and i have a question. I am calling a specific Url site with the following code:
NSURL *Url = [NSURL URLWithString:[requestStream stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *htmlString = [NSString stringWithContentsOfURL:Url encoding:NSUTF8StringEncoding error:&error];
Then i create an nsstring and print it with the NSLog and i got the following results:
2014-05-14 15:50:58.118 jsonTest[1541:907] Data : Array
(
[url] => http://sheetmusicdb.net:8000/hnInKleinenGruppen
[encoding] => MP3
[callsign] => SheetMusicDB.net - J
[websiteurl] =>
)
My question in how can i parse the URL link and then use it as a value? I tried to put them to an array or a dictionary but i get error back. So if anyone can help me i would appreciate it.
Ok i managed to grab the link with the following code:
if(htmlString) {
//NSLog(#"HTML %#", htmlString);
NSRange r = [htmlString rangeOfString:#"=>"];
if (r.location != NSNotFound) {
NSRange r1 = [htmlString rangeOfString:#"[encoding]"];
if (r1.location != NSNotFound) {
if (r1.location > r.location) {
_streamTitle = [htmlString substringWithRange:NSMakeRange(NSMaxRange(r), r1.location - NSMaxRange(r))];
NSLog(#"Title %#", _streamTitle);
}
}
}
} else {
NSLog(#"Error %#", error);
}
Thank you for your suggestions. My problem now is that i pass the string into an avplayer and i can't hear music.
I think this will be help for you..
// #property (nonatomic,retain) NSMutableData *responseData;
// #synthesize responseData;
NSString *urlString=#"http:your urls";
self.responseData=[NSMutableData data];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self];
NSLog(#"connection====%#",connection);
JSON Delegates :
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
self.responseData=nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *response_Array = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
// Write code for retrieve data according to your Key.
}
Try This:
NSString *urlStr=[NSString stringWithFormat:#"uRL"];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
if (theConnection)
{
receivedData=[[NSMutableData data] retain] ;
}
#pragma mark - Connection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// append the new data to the receivedData
// receivedData is declared as a method instance elsewhere
//NSLog(#"data %#",data);
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// release the connection, and the data object
// [connection release];
// [receivedData release];
UIAlertView *prompt = [[UIAlertView alloc] initWithTitle:#"Connection Failed" message:[error localizedDescription]delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[prompt show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *content = [[NSString alloc] initWithBytes:[receivedData bytes]
length:[receivedData length] encoding: NSUTF8StringEncoding];
NSData *jsonData = [content dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
}

NSURLConnection delegate methods

I am using a button action to update the value of a MySQL table field. The update is perform in the web server, but I need to update a UILabel text in my view Controller.
This is the code I have implemented:
- (IBAction)votarAction:(id)sender {
//URL definition where php file is hosted
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
dispatch_async(backgroundQueue, ^{
int categoriaID = [[detalleDescription objectForKey:#"idEmpresa"] intValue];
NSString *string = [NSString stringWithFormat:#"%d", categoriaID];
NSLog(#"ID EMPRESA %#",string);
NSMutableString *ms = [[NSMutableString alloc] initWithString:#"http://mujercanariasigloxxi.appgestion.eu/app_php_files/cambiarvaloracionempresa.php?id="];
[ms appendString:string];
// URL request
NSLog(#"URL = %#",ms);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];
//URL connection to the internet
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
dispatch_async(dispatch_get_main_queue(), ^{
//update your label
});
});
}
#pragma NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//buffer is the object Of NSMutableData and it is global,so declare it in .h file
buffer = [NSMutableData data];
NSLog(#"ESTOY EN didReceiveResponse*********");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"ESTOY EN didReceiveDATA*********");
[buffer appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Here You will get the whole data
NSLog(#"ESTOY EN didFINISHLOADING*********");
NSError *jsonParsingError = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:buffer options:0 error:&jsonParsingError];
//And you can used this array
NSLog(#"ARRAY = %#",array);
//HERE LABEL.TEXT UPDATE CODE
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR de PARSING");
NSLog(#"ESTOY EN didFAILWITHERROR*********");
}
As I told you, the field value at the MySQL table is updated every time the button is tapped, but the problem is that the NSURLConnection delegate methods are never called.
Any help is welcome
In your view controller's header file add: <NSURLConnectionDelegate>
Also, there's no need to throw the NSURLConnection into a seperate background process, maybe that's why the delegates aren't called. NSURLConnection is already asynchronous
Perhaps try something like this:
- (IBAction)votarAction:(id)sender
{
int categoriaID = [[detalleDescription objectForKey:#"idEmpresa"] intValue];
NSString *originalString = [NSString stringWithFormat:#"%d", categoriaID];
NSMutableString *mutablesString = [[NSMutableString alloc] initWithString:#"http://mujercanariasigloxxi.appgestion.eu/app_php_files/cambiarvaloracionempresa.php?id="];
[mutableString appendString:originalString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:mutableString]];
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
request.timeoutInterval = 5.0;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (data)
{
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
dispatch_async(dispatch_get_main_queue(), ^
{
// Update your label
self.label.text = [array objectAtIndex:someIndex];
});
}
else
{
// Tell user there's no internet or data failed
}
}];
}

how to store json data from url in ios device and to use local it

I want to use json in my application. I can parse json from url with this code :
#import "ViewController.h"
#implementation ViewController
{
NSDictionary *titles;
NSMutableData *Data;
NSArray *fileContent;
NSArray *folderContent;
NSMutableArray *all;
}
#synthesize Table;
- (void)viewDidLoad
{
[super viewDidLoad];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url =[NSURL URLWithString:#"http://192.168.1.100/veis/root/developers/api/filemanager.php?key=5147379269&getlist=root"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
- (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;
titles = [NSJSONSerialization JSONObjectWithData:Data options:kNilOptions error:nil];
fileContent = [titles objectForKey:#"fileContent"];
folderContent = [titles objectForKey:#"folderContent"];
all = [[NSMutableArray alloc]init];
[all addObjectsFromArray:folderContent];
[all addObjectsFromArray:fileContent];
[Table reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"The Connection has been LOST" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
but I want when I dont have internet I can to use of json. I dont know how to use of json in way offline (or local in my device)
can you guide me in this issue that how to use json in way offline
The way parsing should be same for Online and Offline json data, both are same, just you need to write a file using Unparsed data say data.json in Documents Directory, if you want to use the same process to use json, but if you want to use parsed json, then write it as plist..
You can try to use the following methods
-(void)saveJsonWithData:(NSData *)data{
NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:#"/data.json"];
[data writeToFile:jsonPath atomically:YES];
}
-(NSData *)getSavedJsonData{
NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:#"/data.json"];
return [NSData dataWithContentsOfFile:jsonPath]
}
Then call the function as
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self saveJsonWithData:data];
}

Show Activity Indicator when fetching JSON data

I am beginner in IOS programming. My question is my app fetching data from JSON in my web server, when starting the apps, it is slightly lag and delay due to the fetching process, so i would like to show activity indicator when i connecting to JSON data. How can i do that?
My JSON coding:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *urlAddress = [NSURL URLWithString:#"http://emercallsys.webege.com/RedBoxApp/getEvents.php"];
NSStringEncoding *encoding = NULL;
NSError *error;
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:&error];
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[jsonreturn release];
}
use the following code
//add a UIActivityIndicatorView to your nib file and add an outlet to it
[indicator startAnimating];
indicator.hidesWhenStopped = YES;
dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
//Load the json on another thread
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:NULL];
[jsonreturn release];
//When json is loaded stop the indicator
[indicator performSelectorOnMainThread:#selector(stopAnimating) withObject:nil waitUntilDone:YES];
});
You can use something like below code:
- (void)fetchData
{
[activityIndicator startAnimating];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *theRequest = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection) {
}
else {
NSLog(#"The Connection is NULL");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
webData = [[NSMutableData data] retain];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction %#",error);
UIAlertView *connectionAlert = [[UIAlertView alloc] initWithTitle:#"Information !" message:#"Internet / Service Connection Error" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[connectionAlert show];
[connectionAlert release];
[connection release];
[webData release];
return;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
//NSLog(#"Received data :%#",theXML);
//[theXML release];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary: webData error:&error];
if (dict) {
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[activityIndicator stopAnimating];
}

URL Connection ios

I want to create connection from my iphone to my website where I will be retrieving data that needs to be parsed. I am not having any luck so far and am kind of confused in regard to the following delegate methods:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
Are these methods called upon there own from my code or do I manually need to call them? Do I need to declare a delegate anywhere in my .h file?
This is what I have been doing but have had no luck. If anyone can explain it would be appreciated. It says my connection is successful made but the NSLog comes up in the console for didFailWithError.
Thanks
-(void) data: (id) sender
{
NSString *stringToBeSent;
NSURL *siteWithNumbers;
NSString *translation;
NSError *error;
NSString *boo;
sender= [sender lowercaseString];
sender= [sender stringByReplacingOccurrencesOfString:#"," withString:#""];
receivedData= [[NSMutableData alloc] init]; //declared in .h file as NSMutableData
stringToBeSent= [[NSString alloc]
initWithFormat:#"http://xxxx/sql.php? data=%#",sender];
NSURLRequest *theRequest=[NSURLRequest
requestWithURL:[NSURL URLWithString:stringToBeSent]];
NSURLConnection *conn= [[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
//[self createConnectionWithPath:stringToBeSent];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
/* appends the new data to the received data */
NSLog(#"here now1");
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
NSString *stringData= [[NSString alloc]
initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Got data? %#", stringData);
[conn release];
conn = nil;
}
- (void)connection:(NSURLConnection *)
connection didFailWithError:(NSError *)error
{
NSLog(#"fail");
}
//in .h file
#interface yourViewController : UIViewController<NSURLConnectionDelegate>
{
NSMutableData *responseData;
}
// in .m file
-(void) data: (id) sender
{
NSString *strWithURL = [NSString stringWithFormat:#"%#%#",TownsServiceURL,state];
strWithURL = [strWithURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"strConfirmChallenge=%#",strWithURL);
NSURL *myURL = [NSURL URLWithString:strWithURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
[NSURLConnection connectionWithRequest:request delegate:self];
}
//Delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection failed with error: %#", [error localizedDescription]);
UIAlertView *ConnectionFailed = [[UIAlertView alloc]
initWithTitle:#"Connection Failed"
message: [NSString stringWithFormat:#"%#", [error localizedDescription]]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[ConnectionFailed show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *s = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
}

Resources