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 :)
Related
As I'm a newbie in iOS development, please help me to parse the JSON output.
My JSON output:
{"sbi":[{"Emp_Id":1001,"Emp_Name":"James","Designation":"Manager","Skills":["C,C++"]},{"Emp_Id":1002,"Emp_Name":"John","Designation":"Asst.Manager","Skills":["Java,PHP"]},{"Emp_Id":1003,"Emp_Name":"Joe","Designation":"Chief Manager","Skills":["Oracle,HTML"]}]}
When we launch an app, I should get sbi on the first view and if I select that particular row, I should get all the details related to sbi on the next view, i.e. EmpId, EmpName, Designation, Skills, ...
Thanks in advance.
Parse the json to a dictionary object with
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:yourJson options:0 error:nil];
Please refer following link to Json parsing Demo.It will help you to learn Json parsing.
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
-(void)Startconnection:(NSString *)urlString
{
NSLog(#"%#",urlString);
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:"your url string "]];
connetion1=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self] ;
webData = [NSMutableData data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// [ShowAlert showMyAlert:#"Network Alert" :#"No Internet connection detected"];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSError *myError = nil;
responceDic=nil;
responceDic = [NSJSONSerialization JSONObjectWithData:webData options:NSJSONReadingMutableLeaves error:&myError];
NSLog(#"%#",responceDic );
}
In the .h file declare NSXMLParserDelegate delegate
#interface webservice : NSObject<NSXMLParserDelegate>
{
NSMutableData * webData;
NSString *currentData;
NSURLConnection * connetion1;
}
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];
}
}
I have tried to find a similar question but I was unable to do so. I have a singleton that is used to gather information through out my app. Once of the values is obtained within the following method.
-(NSString *)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data-(NSString *)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
In this method I get the response from th webservice that I am trying to connect to. Everything is good. However any attempt to save the variable value to my singleton fails. Within this method no problem. When I try to get to the next view and reference my singleton, it is as if the value never gets saved.
Here is a skeleton of my code.
NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
[jsonResponse setHostedURL:_hostedURL];
Basically the goal here is to have the hosted payment page appear in the next view. The flow flow for that works. I just need to pass the URI link so that payment can be made.
I know that I can return a value from this delegate method, but since I never explicitly call this method, so I am unsure where it is being called. Probably the reason why my values are not being saved in the singleton class.
EDIT:
Right now I have one view which does all of the action.
//
// NBXViewController.h file
#import <UIKit/UIKit.h>
#interface NBXViewController : UIViewController
//*************************************************
// Variables to be declared for NBXViewController *
//*************************************************
#property (strong, nonatomic) IBOutlet UILabel *storeLabel;
#property (strong, nonatomic) IBOutlet UIButton *purchaseButton;
#property (strong, nonatomic) IBOutlet NSString *hostedURL;
//*************************************************
// Button Action methods for the buttons on View *
//*************************************************
- (IBAction)puchaseButtonAction:(id)sender;
//*************************************************
// Connection Delegate Methods *
//*************************************************
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; // Handle Connection Error
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; // Data Received from Connection (Header Information)
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; //Response from Connection (Return from Hosted being called)
-(void)connectionDidFinishLoading:(NSURLConnection *)connection; // Coonection did finish loading
#end
Implementation file.
//
// NBXViewController.m
// HostedAPI
//
// Created by Philip Teoli on 3/1/2014.
// Copyright (c) 2014 Philip Teoli. All rights reserved.
//
#import "NBXViewController.h"
#import "NBXJSONResponse.h"
#interface NBXViewController ()
#end
#implementation NBXViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//****************************************
// PurchaseButton Action Method *
//****************************************
- (IBAction)puchaseButtonAction:(id)sender
{
//************************************
// Building JSON Request *
//************************************
NSString *jsonString = #"Sample Request";
//**************************************
// Convert JSON String to NSData *
//**************************************
NSData* jsonRequestData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//**************************************
// Creating JSON object to Send *
//**************************************
NSString *jsonRequest = [[NSString alloc] initWithData:jsonRequestData encoding:NSUTF8StringEncoding];
//*****************************************
// Base64 Encoding for Application Header *
//*****************************************
NSString *base64Signature = #"NbMIIkomZ8mFNw97EGRT:NAA5e965731e8a27ab11f5f";
NSString *basic = #"Basic: ";
NSData *base64SignatureData = [base64Signature dataUsingEncoding: NSUTF8StringEncoding];
NSString *base64SignatureEncoded = [base64SignatureData base64EncodedStringWithOptions:0];
NSString *header = nil;
header = [basic stringByAppendingString:base64SignatureEncoded];
// NSLog(#"Encoded Header: %#", header);
//*************************************
// Preparing to send XML through POST *
//*************************************
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[jsonRequest length]]; //Calculating the Content Length
NSData *postData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding]; // preapring JSON Request to be sent
//**************************************
// Headers and POST Body *
//**************************************
NSURL *serviceUrl = [NSURL URLWithString:#"https://pay.test.ewbservice.com/orders"];
NSMutableURLRequest *serviceRequest=[NSMutableURLRequest requestWithURL:serviceUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[serviceRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[serviceRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[serviceRequest setValue:header forHTTPHeaderField:#"Authorization"];
[serviceRequest setHTTPMethod:#"POST"];
[serviceRequest setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:serviceRequest
delegate:self startImmediately:YES];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
[connection start];
NSLog(#"Hosted URL in Button: %#", _hostedURL);
}
//****************************************************
// Implementation of Connection Delegate Methods *
//****************************************************
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"did fail");
}
//*******************************************************
// Connection Data Received *
//*******************************************************
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *dataResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData: [dataResponse dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
//********************************
// Iterating through Dictionary *
//********************************
NSArray *jsonLink = nil;
for(id key in jsonDictionary)
{
if ([key isEqualToString:#"link"])
{
jsonLink = [jsonDictionary objectForKey:key]; // this returns a dictionary. Will need to parse dictionary another 2 times to get proper URI.
}
}
NSDictionary *test = [jsonLink objectAtIndex:0];
for(id key in test)
{
if ([key isEqualToString:#"uri"])
{
_hostedURL = [test objectForKey:key];
}
}
NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
[jsonResponse setHostedURL:_hostedURL];
}
//*******************************************************
// Connection Response Method *
//*******************************************************
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"did receive response: \n %#", response);
NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
[jsonResponse setHostedURL:_hostedURL];
}
//*******************************************************
// Connection Finished Loading Data Method *
//*******************************************************
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"did finish loading!!! \n%#", _hostedURL);
// NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
// [jsonResponse setHostedURL:_hostedURL];
}
#end
Please let me know of your thoughts. I can post more details if needed. Thanks in advance for your help!!!
Regards,
Thanks to the great help from #rdelmar I was able to get through this. Basically in short what was happening was that I was going to the next view before the information was received by my previous view from the web service. So when I was trying to change a label with a value to my Singleton, it was not stored yet. How I got around the issue is that when I click a button I wait until the web services responses and then I add a view to go to the new view. Now my URL that I was waiting reaches me, I save it to Singleton and then I go to the next view.
I will add my code once I can grab it and post it.
Thanks again for all of your help Eric!!! Your patience and help make you a great person on this community.
Regards,
Corporate One
I want to update my json file in ios app which is offline compiled in the app. When the app is refreshed the file should get updated from the server : localhost:8888/ios/ios_app/Service/data.json
Please help...
Thank you in advance
I use SOAP when i need get value that can be serialized to a string type. But if all what you need is json file, look at NSURLConnection class.
- (void)downloadJSONFromURL {
NSURLRequest *request = ....
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
// ...
}
NSData *urlData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
urlData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[urlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *jsonParsingError = nil;
id object = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
if (jsonParsingError) {
DLog(#"JSON ERROR: %#", [jsonParsingError localizedDescription]);
} else {
DLog(#"OBJECT: %#", [object class]);
}
}
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"];
}
}