I know only getting data for Json.But i need how to getting data for two json url.
i have two Urls and two MutableArrays.Ever time i can handle only one url like this :-
NSURL * url=[NSURL URLWithString:#" url"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:req delegate:self];
if(connection)
{
NSLog(#"Connected");
webData=[[NSMutableData alloc]init];
NSLog(#"Connected2");
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
return arrayfirst.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
return arrayfirst[row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
one.text = arrayfirst[row];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableArray *al=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSLog(#"the array is %#",al);
for(NSArray *arr in al)
{
[arrayfirst addObject:[arr objectAtIndex:1]];
}
}
Please give me any idea about how to handle two Json url. I have two urls BusinessCategory and BusinessLocation I have two MutableArrays arrayfirst and arraysecond. I know about BusinessCategory data pass to arrayfirst. But I don't know how to handle.
You have to create two NSURL connection and handle the response in the delegate.
So, in your header file you can have:
NSURLConnection *conn1;
NSURLConnection *conn2;
NSMutableArray *arrayFirst;
NSMutableArray *arraySecond;
In the implementation file:
//Connection 1
NSURL *url1=[NSURL URLWithString:#"yourjsonurl1"];
NSURLRequest *request1 = [NSURLRequest requestWithURL:url1];
conn1=[[NSURLConnection alloc] initWithRequest:request1 delegate:self];
//Connection 2
NSURL *url2=[NSURL URLWithString:#"yourjsonurl2"];
NSURLRequest *request2 = [NSURLRequest requestWithURL:url2];
conn2=[[NSURLConnection alloc] initWithRequest:request2 delegate:self];
//In your delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (connection==conn1) {
arrayFirst = [[NSMutableData alloc]init];
}
else if (connection==conn2){
arraySecond = [[NSMutableData alloc]init];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (connection==conn1) {
[arrayFirst appendData:data];
}
else if (connection==conn2){
[arraySecond appendData:data];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if (connection==conn1) {
NSLog(#"SOMETHING WENT WRONG WITH URL1");
}
else if (connection==conn2){
NSLog(#"SOMETHING WENT WRONG WITH URL2");
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (connection==conn1) {
NSLog(#"DONE WITH URL1");
}
else if (connection==conn2){
NSLog(#"DONE WITH URL2");
}
}
A shorter (and maybe, better) way of doing this is to run it in an asynchronous operation:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *result = [NSData dataWithContentsOfURL:"yourURL"];
id jsonResult;
if ([result length] != 0) { jsonResult = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];}
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"done!");
});
});
Related
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"]];
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];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];(URL1)
self.jsonData = [[NSMutableData alloc]init];(URL2)
self.genderData = [[NSMutableData alloc]init];(URL3)
}
I want to send multiple url at a time what the process to receive response..?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.responseData length]);
NSError * error;
id result = (NSMutableArray *)[NSJSONSerialization JSONObjectWithData:self.jsonData options:kNilOptions error:&error];
if (error)
{
NSLog(#"DATA LOAD ERROR");
}
else
{
if([result isKindOfClass:[NSArray class]])
{
titlesArray = result;
}
else
{
titlesDic = result;
}
}
[self genderURLMethod];
}
This is another Delegate Method
When working with NSURLConnection, I tend to go one of two ways.
Always use a different class for each delegate. That way the delegate instance only has to worry about 1 URL.
Use [[connection originalRequest] URL] to distinguish between the different URLs.
Example:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *URLString = [[[[connection originalRequest] URL] absoluteString];
if ([URLString isEqualToString:MY_URL_1]) {
// Handle the response for the first URL.
} else if ([URLString isEqualToString:MY_URL_2]) {
// Handle the response for the second URL/
}
}
In my app I'm starting NSURLConnection, parsing XML, initialize array from this XML, and show it in the tableView. In ViewDidLoad I appeal to the server with a query parameter 0 , and it's returned for me string, after all conversion a have in tableView 4 rows - titles, and when i push on some of this titles, all process (connection to the server, parsing, arrays initialising, ) must be repeated. In didSelectedRowAtIndexPath I have to transmit section ID (so that the server sent me the correct data). How can I do it correctly? I'm establish connection in ViewDidLoad, how can I call it again?
My .m file:
#import "catalogViewController.h"
#import "XMLReader.h"
#interface catalogViewController ()
#end
#implementation catalogViewController
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) { } return self;
}
//-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-CONNECTIONS METHOD START-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
[_receivedData release];
NSString *errorString = [[NSString alloc] initWithFormat:#"Connection failed! Error - %# %# %#", [error localizedDescription], [error description], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; NSLog(#"%#",errorString);
[errorString release];
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-GET FULL DATA HERE-=-=-=-=-=-=-=-=--=-=-=-=-=-=-
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *dataString = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
NSString *testXMLString = [NSString stringWithContentsOfURL:myURL usedEncoding:nil error:nil];
// -=-=-=-=-=-=-=-=-=-=Parse the XML into a dictionary-=-=-=-=-=-=-=-=-=-=
NSError *parseError = nil;
_xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART END-=-=-=-=-=-=-=
_titleArr = [[NSArray alloc] initWithArray:[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"name"] valueForKey:#"text"]];
_IDArr = [[NSArray alloc] [[[_xmlDictionary objectForKey:#"result"] objectForKey:#"id"] valueForKey:#"text"]];
_priceArr= [[NSArray alloc][[[_xmlDictionary objectForKey:#"result"] objectForKey:#"price"] valueForKey:#"text"]];
_ImageURLArr=[[NSArray alloc][[[_xmlDictionary objectForKey:#"result"] objectForKey:#"img"] valueForKey:#"text"]];
[connection release];
[_receivedData release];
[dataString release];
_didDataLoaded=TRUE;
[_myTableView reloadData]; // IBOutlet property
[self.tableView reloadData]; //default
}
//-=-=-=-=-=-=-=-=-=-=-Connection methods END-=-=-=-=-=-=-=-=-=-
- (void)viewDidLoad {
[super viewDidLoad];
_didDataLoaded=FALSE;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//-=-==-=-=-=-=-=-=-=-=-=-=--=-=START Shit with connection-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=
NSString* params = #"request_params";
NSURL* url = [NSURL URLWithString:#"my URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"POST";
request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(#"Connecting...");
_receivedData = [[NSMutableData data] retain];
} else {
NSLog(#"Connecting error");
}
}
//-=-==-=-=--=-==-=-=-=-=-=--=-==---=-=--==-=-=-=-=-TableView methods-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=--=-=-=-=-=-=-=
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (_didDataLoaded == FALSE) {
return 1;
}
else return self.titleArr.count;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { return 1; }
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"creatures"];
UIImage *creatureImage = nil;
if (_didDataLoaded == FALSE) {
cell.textLabel.text=#"Downloading...";
cell.detailTextLabel.text= #"downloading...";
} else {
cell.textLabel.text = [self.titleArr objectAtIndex:indexPath.row];
cell.detailTextLabel.text= _IDArr[indexPath.row];
NSString *img = self.ImageURLArr[indexPath.row];
creatureImage =[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img]]]; cell.imageView.image = creatureImage;
}
return cell;
}
#end
You can move the relevant code from viewDidLoad to a specific method, something like:
- (void)loadXMLData {
// Initiate your loading/parsing
}
In viewDidLoad just call this method:
- (void)viewDidLoad {
[super viewDidLoad];
[self loadXMLData];
}
This way you can call [self loadXMLData] multiple times.
However... be careful with calling [tableView reloadData] from inside a UITableViewDelegate method implementation, as this will cause the tableview to call (at least some of the) delegate methods, which can cause recursive loops or other odd behaviour.
I am parsing 5 urls here using NSURLConnection delegate which retrieves json from mysql db & inserts into core data to DB while user logs in. But the code is taking too much time,how can I reduce time here please help.
dispatch_queue_t myBackgroundQueue;
myBackgroundQueue = dispatch_queue_create("loginTask", NULL);
dispatch_async(myBackgroundQueue, ^(void){
// code for parsing 5 urls
json_parser *obj= [[json_parser alloc]init];
[obj parseUrl:#"myurl"];
});
#interface json_parser () {
NSMutableArray *array;
NSMutableData *mdata;
NSURLConnection *conn;
}
#end
#implementation json_parser
- (void)parseUrl:(NSString *)baseUrl
{
NSURL *url=[NSURL URLWithString:baseUrl];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
conn=[NSURLConnection connectionWithRequest:request delegate:self];
if(conn) {
mdata=[[NSMutableData alloc]init];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[mdata setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mdata appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allData=[NSJSONSerialization JSONObjectWithData:mdata options:0 error:nil];
for (NSDictionary *dict in allData)
{
masterGeneric *masterObj=[[masterGeneric alloc]init];//this is nsobject type class
masterObj.masterId=[dict objectForKey:#"id"];
masterObj.genericname=[dict objectForKey:#"genericname"];
masterObj.salient_features=[dict objectForKey:#"salient_features"];
masterObj.bioactivity_group=[dict objectForKey:#"bioactivity_group"];
masterObj.therapy_group=[dict objectForKey:#"therapy_group"];
masterObj.dosage_information=[dict objectForKey:#"dosage_information"];
masterObj.indications=[dict objectForKey:#"indications"];
masterObj.food=[dict objectForKey:#"food"];
masterObj.interaction=[dict objectForKey:#"interaction"];
masterObj.side_effects=[dict objectForKey:#"side_effects"];
masterObj.precautions=[dict objectForKey:#"precautions"];
masterObj.warnings=[dict objectForKey:#"warnings"];
masterObj.advice_to_patients=[dict objectForKey:#"advice_to_patients"];
masterObj.route_of_administration=[dict objectForKey:#"route_of_administration"];
masterObj.available_form=[dict objectForKey:#"available_form"];
}
}