App getting frozen while parsing json - ios

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

Related

Is it possible to call web services like JSON parsing from Appdelegate method for "POST" in objective C?

Is it possible to call web services like JSON parsing from AppDelegate.m class for "POST"?
I want to post data to server using web Service as application starts .
#pragma mark JSON Delegates
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
responseData = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *DictData = (NSDictionary*)[responseString JSONValue];
}
here I attach the sample method add this in your AppDelegate.h
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSURLConnection *clearSession;
NSMutableData * responseData;
}
in your AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self clearsession]; // this is your method Name
return YES;
}
-(void)clearsession
{
// call the clear session
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:#"yourURLName.php"]];
// get the session ID and UserID from Sqlite
NSString *requestString = [NSString stringWithFormat:#"user_id=%#",passyourString,nil];
NSMutableData *requestData =[NSMutableData dataWithBytes:[requestString UTF8String] length: [requestString length]];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: requestData];
clearSession = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[clearSession start];
}
#pragma mark - NSUrlConnectionDelegate Methods
-(void)connection:(NSConnection*)conn didReceiveResponse:(NSURLResponse *)response
{
if (responseData == NULL)
{
responseData = [[NSMutableData alloc] init];
}
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *customAlert = [[UIAlertView alloc]initWithTitle:#"No NetWork" message:#"Interet Connection is Lost" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[customAlert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData: responseData options: kNilOptions error:nil];
NSString *str=[jsonDict objectForKey:#"result"];
if ([str isEqualToString:#"success"])
{
// Add your Home Viewcontroller
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle: nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:#"yourIDentifierName"];
self.window.rootViewController=viewController;
}
else
{
// do ur stuff here
}
}
choice no-2
use this link , this is protocol method
You can. Check out AFNetworking as a good example to parse json data. I don't recommend you put parsing in app delegate. This delegate just handle things that is before root view controller get a chance to run.
Have you specify you follow the delegate protocol? Based on your code we cannot know.

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

Json response is giving wrong data

I am calling the webservice string using the NSURLConnection , I am getting wrong data in response in success method of NSURLConnection , But if i load same URL in browser i am getting correct response. I am using below code .
NSData *mydata=[srtRes dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSMutableArray *returnArry =[[NSMutableArray alloc]init];
returnArry = [NSJSONSerialization JSONObjectWithData:mydata options:NSJSONReadingMutableContainers error:&e];
How to resolve this issue. Kindly give suggestion and answers.
Try this one :
// In .h class
#property (nonatomic,retain) NSMutableData *responseData;
#property (nonatomic, retain) NSMutableArray *temp_arr;
// In .m class
#synthesize responseData;
#synthesize temp_arr;
- (void)viewDidLoad
{
NSString *urlString=#"http://your urls";
self.responseData=[NSMutableData data];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self];
NSLog(#"connection====%#",connection);
}
Delegate Method of JSON Parsing :
-(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 * returnArry = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
NSDictionary *nameDic = nil;
for (int i = 0 ; i < [returnArry count]; i++)
{
nameDic = [returnArry objectAtIndex:i];
[self.temp_arr addObject:[nameDic objectForKey:#"name"]]; // According your key you have to save data in temp_arr.
}
}
Please follow this , if any doubt let me know :)

NSURLConnection with ARC not receiving Data

I'm fairly new to iOS Development and I'm trying to get content from an URL. I'm using the Apple tutorial for using NSURLConnection, everything is working but I'm not getting data. I've looked around and couldn't find an answer to my problem. I'm also using ARC in my project, maybe that causes the problem?
Here is the code I'm using, starting with my header file:
#interface ViewController : UIViewController
#property (nonatomic, retain) NSMutableData *receivedData;
#end
implementation file:
#implementation ViewController
#synthesize receivedData;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"1. viewDidLoad");
// Create the request
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.apple.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// Create the connection with the request and start loading the data
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(#"2. connection succeeded");
receivedData = [NSMutableData data];
} else {
NSLog(#"2. connection failed");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"3. didReceiveResponse");
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"4. Connection failed! Error - %# %#", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"4. Succeeded! Received %d bytes of data", [receivedData length]);
}
All the NSLog are working, but it keeps saying receivedData has 0 bytes. I couldn't find an answer to my problem so I hope I can find my answer with this question.
I have translated the Using NSURLConnection part of the URL Loading System Programming Guide using ARC.
//
// MyConnection.h
//
#import <Foundation/Foundation.h>
#interface MyConnection : NSObject
- (void)start;
#property NSMutableData *receivedData;
#end
//
// MyConnection.m
//
#import "MyConnection.h"
#implementation MyConnection
- (void)start {
// Create the request
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.apple.com"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// Create the connection with the request and start loading the data
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMUtableData to fold the received data
// ReceivedData is an instance variable declared elsewhere
_receivedData = [NSMutableData data];
}
}
- (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
{
// Inform the user
NSLog(#"Connectionfailed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Do something with the data
NSLog(#"Succeeded! Recevied %d bytes of data", [_receivedData length]);
}
#end
Just for the sake of completion. I've had the same problem, with cause in threading. If the thread that owns the NSURLConnection object is different than the thread that owns the delegate, the delegate will not receive notifications. That means that the error in connection would also be gone.
So make sure you create NSURLConnection on same thread that you created the delegate.
You need to start the connection.
You could, for example, use – initWithRequest:delegate:startImmediately:.
An even smaller change to your existing code would be to just use - start on your connection on the if branch:
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:request
delegate:self
startImmediately:NO
];
if (connection) {
NSLog(#"2. connection succeeded");
receivedData = [NSMutableData data];
[connection start];
} else {
NSLog(#"2. connection failed");
}
You can find the reference manual for NSURLConnection here

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