How to pass multiple parameters in URL to web View in iOS? - ios

I have following dictionary:
NSDictionary *param = #{#"schoolid":#"schooldb1",
#"token":del.tokenString,
#"mobile":del.phoneString
};
NSLog(#"param:%#",param);
I want to send this parameters (schoolid, token, mobile) to web view. But I don't know how to send that. I tried to search on internet but I didn't get any proper solution for my question.
My main URL is:
NSString *url=#"https://MyURL.com/School/AppSingleTrack";
and I'm going to call UIWebview like following:
NSString *finalurl=[NSString stringWithFormat:#"https://MyURL.com/School/AppSingleTrack/?%#",param];
NSURL *nsurl=[NSURL URLWithString:finalurl];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[_webview loadRequest:nsrequest];
[self.view addSubview:_webview];

Try like this,
NSDictionary *param = #{#"schoolid":#"schooldb1",
#"token":del.tokenString,
#"mobile":del.phoneString
};
NSLog(#"param:%#",param);
NSString *url=#"https://24x7tracker.com/School/AppSingleTrack";
NSString *finalurl=[NSString stringWithFormat:#"https://24x7tracker.com/School/AppSingleTrack/"];
NSURL *nsurl=[NSURL URLWithString:finalurl];
NSMutableURLRequest *nsrequest=[NSMutableURLRequest requestWithURL:nsurl];
NSData *data = [NSJSONSerialization dataWithJSONObject:param options:0 error:nil];
[nsrequest setHTTPBody:data];
[_webview loadRequest:nsrequest];
[self.view addSubview:_webview];
set request's necessary properies if require like [nsrequest setHTTPMethod:#"GET"]; or POST and contentType etc.
You should use AFNetworking, It will make it more easier.

Use this Code,
NSString *sUrl = #"https://24x7tracker.com/School/AppSingleTrack";
NSMutableURLRequest *res = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sUrl]];
[res setHTTPMethod:#"POST"];
NSDictionary *params; = [NSDictionary dictionaryWithObjectsAndKeys:
#"schooldb1",#"schoolid",
del.tokenString,#"token",
del.phoneString,#"mobile",
nil];
NSMutableArray *pairArray = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in params)
[pairArray addObject:[NSString stringWithFormat:#"%#=%#", key, params[key]]];
[res setHTTPBody:[[pairArray componentsJoinedByString:#"&"] dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:res
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"request URL : %#",res.URL);
NSLog(#"request Method : %#",res.HTTPMethod);
NSLog(#"parameters : %#",params);
NSLog(#"response : %#",response);
Resp *r = [ [Resp alloc] initWithDictionary:[NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error:nil]];
// Success - Show Sucess message
if ([r.sCode isEqualToString:#"success"]) {
NSLog(#"response message : %#",r.sData);
}
}];
Use the Class Resp:
Resp.h
#import <Foundation/Foundation.h>
#interface Resp : NSObject
#property (nonatomic, copy) NSString *sCode;
#property (nonatomic, copy) NSString *sMessage;
#property (nonatomic, copy) NSString *sData;
- (id)initWithDictionary:(NSDictionary *)dictionary;
#end
Resp.m
#import "Resp.h"
#implementation Resp
#synthesize sCode = _id;
#synthesize sMessage = _title;
#synthesize sData = _data;
- (id)initWithDictionary:(NSDictionary *)dictionary {
self = [super init];
if (self) {
self.sCode = [dictionary objectForKey:#"code"];
self.sMessage = [dictionary objectForKey:#"message"];
self.sData = [dictionary objectForKey:#"data"];
}
return self;
}
#end
then finally get the response, hope its helpful

Firstly, talk to your colleague or check the documents of the URL, to confirm what format of parameters the API needs, and the Request method, such as GET or POST.
Secondly, concatenate the params to the proper format, and don't forget escape the parameters.
If your URL need parameters as normal, try these:
NSDictionary *params = #{#"schoolid" : #"",
#"token" : #"",
#"mobile" : #""};
NSMutableArray *keyValues = [NSMutableArray array];
for (NSString *key in params) {
[keyValues addObject:[NSString stringWithFormat:#"%#=%#&", key, params[key]]];
}
NSString *paramsString = [keyValues componentsJoinedByString:#"&"];
paramsString = [paramsString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
// Don't add / at last unless the URL has, because / is another path
NSString *baseURL = #"https://24x7tracker.com/School/AppSingleTrack";
// If GET, you can use these two lines, or use below
// NSString *urlString=[NSString stringWithFormat:#"%#?%#", baseURL, paramsString];
// NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
// if POST
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:baseURL]];
request.HTTPMethod = #"POST"; // Default is GET, you can send get request by default,
request.HTTPBody = [paramsString dataUsingEncoding:NSUTF8StringEncoding];
[webView loadRequest:request];
Edit:
According to #Shubhank's guess, if the webview's request via ajax, you should confirm the function of javascript, and try these codes in webview's delegate webViewDidFinishLoad:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"javascriptFunction(%#, %#, %#)", param1, param2, param3]];
}

Related

Adding Rotten Tomates API to iphone app

Im trying to add Rotten Tomatoes API to my app but it doesn't seem to like it? What am I doing wrong?? The error says "Data Argument not used by format string"
-(void)main {
NSLog(#"Service has run");
NSString *api_key = #"j4jz49tvf76cmnb4mwfyjvyt";
NSString *search_term = [searchTerm stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString *url = [NSString stringWithFormat:#"http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit=16&country=us&apikey=j4jz49tvf76cmnb4mwfyjvyt", api_key, search_term];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
if (responseData !=nil) {
NSError *error =nil;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:&error];
if (error) {
[delegate serviceFinished:self withError:YES];
} else {
results = (NSArray *) [json valueForKey:#"movies"];
[delegate serviceFinished:self withError:NO];
}
} else {
[delegate serviceFinished:self withError:YES];
}
}
#end
Your error is on this line
NSString *url = [NSString stringWithFormat:#"http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit=16&country=us&apikey=j4jz49tvf76cmnb4mwfyjvyt", api_key, search_term];
String with format works with adding a data argument like %# in a string as a placeholder, and then replacing that with the following arguments in your method call.
What you want to do is probably something like:
NSString *url = [NSString stringWithFormat:#"http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit=16&country=us&apikey=%#&search_term=%#", api_key, search_term];

The correct way asynchronously call an object?

I have hobbled together one of my first objects. The goal of the object is to send a text message, which is does. However I'm calling it from the 2nd UIViewController within ViewDidLoad, and its still hanging within the Segue transition. So I know I need to get it asynchronously, but reading some other threads they implied that the proper way to go around it is to make it an "AppDelegate Object", so I would assume I would need to call the object from the AppDelegate, but I'm not really sure about how to go about that as I have not really worked with that in some tutorials I'm doing, and on top of that, is that the correct way to go about using my object?
initializing the object from my view controller
Twilio *twilio = [[Twilio alloc] init];
[twilio sendMessage: self.phoneNumber: [self getRandomNumberBetween:1000 to:9999]];
Header file
#import <Foundation/Foundation.h>
#interface Twilio : NSObject
#property (strong, nonatomic) NSString *TwilioSID;
#property (strong, nonatomic) NSString *TwilioSecret;
#property (strong, nonatomic) NSString *FromNumber;
#property (strong, nonatomic) NSString *ToNumber;
#property (strong, nonatomic) NSString *Message;
-(id)init;
-(id)sendMessage:(NSString *)phoneNumber :(NSString *)message;
#end
Implementation file
#import "Twilio.h"
#implementation Twilio
-(id)init {
self = [super init];
if(self) {
// Twilio Common constants
self.TwilioSID = #"A....3";
self.TwilioSecret = #"e...8";
self.FromNumber = #"5...2";
self.ToNumber = nil;
self.Message = nil;
}
return self;
}
-(id)sendMessage:(NSString *)phoneNumber :(NSString *)message
{
NSLog(#"Sending request.");
self.ToNumber = phoneNumber;
self.Message = message;
// Build request
NSString *urlString = [NSString stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages", self.TwilioSID, self.TwilioSecret, self.TwilioSID];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
// Set up the body
NSString *bodyString = [NSString stringWithFormat:#"From=%#&To=%#&Body=%#", self.FromNumber, self.ToNumber, self.Message];
NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
NSError *error;
NSURLResponse *response;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Handle the received data
if (error) {
NSLog(#"Error: %#", error);
} else {
NSString *receivedString = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Request sent. %#", receivedString);
}
return self.Message;
}
#end
Updated
With recommendation below I changed my object implementation like so:
//NSError *error;
//NSURLResponse *response;
//NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[NSURLConnection sendAsynchronousRequest:request queue:self.queue completionHandler:^(NSURLResponse *response, NSData *data, NSError
*error) {
// Handle the received data
if (error) {
NSLog(#"Error: %#", error);
} else {
NSString *receivedString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Request sent. %#", receivedString);
}
NSLog(#"%#",response);
}];
Use method sendAsynchronousRequest:queue:completionHandler:
See it : https://stackoverflow.com/a/9270711/2828120

Load URL within JSON in UIWebView?

My JSON reads like this:
{
"sites": [
{
"name": "lovely.com",
"url": "http:\/\/www.trial.com\/lovely\/",
"price": "1795",
},
{
"name": "great.com",
"url": "http:\/\/www.trial.com\/great\/",
"price": "1730",
},
{
"name": "food.com",
"url": "http:\/\/www.trial.com\/food\/",
"price": "1195",
},
I need the url of the specified site to open in a separate UIWebView when the user clicks on the "buy" button. Here is a snippet of my current code:
ViewController.m
-(void)buyBttnPressed:(id)sender{
UIWebView *buyView = [[UIWebView alloc] initWithFrame:CGRectMake(20,132,280,368)];
buyView.backgroundColor = [UIColor whiteColor];
buyView.scalesPageToFit = YES;
buyView.delegate = self;
[self.view addSubview:buyView];
// [buyView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
}
I have already parsed the JSON file. I'm just trying to figure out how to open the url(s) in the WebView using the url object key . . .
You can modify code as below
NSString *urlString=[NSString stringWithFormat:#"%#",url];
[buyView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlstring]]];
////(OR) If are using NSObject say Location to store the details you can refer below code
UIButton *btn=(UIButton *)sender;
Location *locObj=[self.dataArray objectAtIndex:btn.tag];
NSString *urlString=[NSString stringWithFormat:#"%#",locObj.url];
[buyView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlstring]]];
int i=-1;
for(NSDictionary *dict in dataarray)
{
i++;
btn.tag=i;
}
Hope it helps you...!
Use the Json element where you saved all the links,let's say that your JsonElement is called
Location
the code should be something like this:
NSURL *nsurl=[NSURL URLWithString:Location.url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webview loadRequest:nsrequest];
do this
NSError *error;
NSJSONSerialization *jsonData = [NSJSONSerialization JSONObjectWithData:parseData options:NSJSONReadingMutableContainers error:&error];
NSString *strURL = [[[jsonData valueForKey:#"sites"]objectAtIndex:selectedIndex]valueForKey:#"url"];
[buyView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:strURL]]];
you can try this
create a custom method to get json data as an array..
-(NSArray *)getDataDictionaryFromJsonFile:(NSString *)jsonFileName
{
NSData *fileContents = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:jsonFileName ofType:#"json"]];
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:fileContents options:kNilOptions error:&error];
NSArray * array = [dict objectForKey:#"sites"];
return array;
}
now call this method where ever you want,
like
NSArray * sitesArray = [self getDataDictionaryFromJsonFile:#"Sites"];
NSURL * url = [NSURL urlFromString:[[sitesArray objectAtIndex:0] objectForKey:#"url"]];
NSLog(#"lovely URL:%#",[[sitesArray objectAtIndex:0] objectForKey:#"url"]);
The easiest way to do that is by using AFNetworking library here
Add AFNetworking to your project and import AFNetworking.h and create a property to store the url from the JSON
//in .h file
#property (strong, nonatomic) NSString *urlFromJSON;
.
//in .m file
NSURL *url = [[NSURL alloc] initWithString:#"YOUR_JSON_URL_HERE"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//You can reach the the url using:
self.urlFromJSON = JSON["url"]; //the key of the url in the JSON
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
Good Luck ;)

Uploading large images using Base64 and JSON

I am using this function to upload an image to a server using JSON. In order to do so, I first convert the image to NSData and then to NSString using Base64. The method works fine when the image is not very large but when I try to upload a 2Mb image, it crashes.
The problem is that the server doesn't receive my image even though the didReceiveResponse method is called as well as the didReceiveData which returns (null). At first I thought it was a time out issue but even setting it to 1000.0 it still doesn't work. Any idea? Thanks for your time!
Here's my current code:
- (void) imageRequest {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.myurltouploadimage.com/services/v1/upload.json"]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [NSString stringWithFormat:#"%#/design%i.png",docDir, designNum];
NSLog(#"%#",path);
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:path]);
[Base64 initialize];
NSString *imageString = [Base64 encode:imageData];
NSArray *keys = [NSArray arrayWithObjects:#"design",nil];
NSArray *objects = [NSArray arrayWithObjects:imageString,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:kNilOptions error:&error];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d",[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSLog(#"Image uploaded");
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse");
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"%#",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}
I finally decided to upload the Base64 image splitting it into smaller substrings. In order to do so, and as I needed many NSURLConnections, I created a subclass named TagConnection which gives a tag for each connection so that there's no possible confusion between them.
Then I created a TagConnection property in MyViewController with the purpose of accessing it from any function. As you can see, there's the -startAsyncLoad:withTag: function that allocs and inits the TagConnection and the -connection:didReceiveData: one which deletes it when I receive a response from the server.
Referring to the -uploadImage function, firstly, it converts the image into string and then splits it and put the chunks inside the JSON request. It is called until the variable offset is larger than the string length which means that all the chunks have been uploaded.
You can also prove that every chunk has been successfully uploaded by checking the server response every time and only calling the -uploadImage function when it returns success.
I hope this has been a useful answer. Thanks.
TagConnection.h
#interface TagConnection : NSURLConnection {
NSString *tag;
}
#property (strong, nonatomic) NSString *tag;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)tag;
#end
TagConnection.m
#import "TagConnection.h"
#implementation TagConnection
#synthesize tag;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)tag {
self = [super initWithRequest:request delegate:delegate startImmediately:startImmediately];
if (self) {
self.tag = tag;
}
return self;
}
- (void)dealloc {
[tag release];
[super dealloc];
}
#end
MyViewController.h
#import "TagConnection.h"
#interface MyViewController : UIViewController
#property (strong, nonatomic) TagConnection *conn;
MyViewController.m
#import "MyViewController.h"
#interface MyViewController ()
#end
#synthesize conn;
bool stopSending = NO;
int chunkNum = 1;
int offset = 0;
- (IBAction) uploadImageButton:(id)sender {
[self uploadImage];
}
- (void) startAsyncLoad:(NSMutableURLRequest *)request withTag:(NSString *)tag {
self.conn = [[[TagConnection alloc] initWithRequest:request delegate:self startImmediately:YES tag:tag] autorelease];
}
- (void) uploadImage {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.mywebpage.com/upload.json"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1000.0];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [NSString stringWithFormat:#"%#/design%i.png", docDir, designNum];
NSLog(#"%#",path);
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:path]);
[Base64 initialize];
NSString *imageString = [Base64 encode:imageData];
NSUInteger length = [imageString length];
NSUInteger chunkSize = 1000;
NSUInteger thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset;
NSString *chunk = [imageString substringWithRange:NSMakeRange(offset, thisChunkSize)];
offset += thisChunkSize;
NSArray *keys = [NSArray arrayWithObjects:#"design",#"design_id",#"fragment_id",nil];
NSArray *objects = [NSArray arrayWithObjects:chunk,#"design_id",[NSString stringWithFormat:#"%i", chunkNum],nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:kNilOptions error:&error];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d",[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[self startAsyncLoad:request withTag:[NSString stringWithFormat:#"tag%i",chunkNum]];
if (offset > length) {
stopSending = YES;
}
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSError *error;
NSArray *responseData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (!responseData) {
NSLog(#"Error parsing JSON: %#", error);
} else {
if (stopSending == NO) {
chunkNum++;
[self.conn cancel];
self.conn = nil;
[self uploadImage];
} else {
NSLog(#"---------Image sent---------");
}
}
}
#end
Please don't think this is the last option, this is just my observation.
I think you should send that NSData in chunks instead of complete Data.
I have seen such methodology in YouTube Video Uploading case.They send the Large set of NSData (NSData of Video File) in Chunks of many NSData.
They uses the Same Methodology for uploading the large data.
So should do google about the Youtube data Uploading API.And you should search out that method , YouTube Uploader Uses.
I hope it may help you .

Convert JSON feed to NSDictionary

Where JSON_CATEGORY_DATA_URL_STRING is my feed URL, which returns fine as:
[
{
"group":"For Sale",
"code":"SSSS"
},
{
"group":"For Sale",
"category":"Wanted",
"code":"SWNT"
}
]
I cannot seem to get a nice NSDictionary (or NSArray) out of the following code:
+ (NSDictionary *)downloadJSON
{
NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:#"%#", JSON_CATEGORY_DATA_URL_STRING];
NSLog(#"%#",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSDictionary *json_dict = (NSDictionary *)json_string;
NSLog(#"json_dict\n%#",json_dict);
NSLog(#"json_string\n%#",json_string);
return json_string;
}
I've read many posts on this, but am not getting it.
With IOS5 you can use NSJSONSerialization for serializing the JSON.
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
You can't just cast a string as a dictionary and expect it to parse the JSON. You must use a JSON parsing library to take that string and convert it into a dictionary.
I made a class that makes this task easier. It uses iOS 5's NSJSONSerialization. Clone it from github here.
You need to use JSON parser. here is the edited code
+ (NSDictionary *)downloadJSON
{
NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:#"%#", JSON_CATEGORY_DATA_URL_STRING];
NSLog(#"%#",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
//JSONValue is a function that will return the appropriate object like dictionary or array depending on your json string.
NSDictionary *json_dict = [json_string JSONValue];
NSLog(#"json_dict\n%#",json_dict);
NSLog(#"json_string\n%#",json_string);
return json_dict;
}
this should be the code to get the NSDictionary. but you json string is an array so instead use .
+ (NSArray *)downloadJSON
{
NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:#"%#", JSON_CATEGORY_DATA_URL_STRING];
NSLog(#"%#",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSArray *json_dict = [json_string JSONValue];
NSLog(#"json_dict\n%#",json_dict);
NSLog(#"json_string\n%#",json_string);
return json_dict;
}
Edit:
you need to use JSON.framework to call JSONValue method.
also you need to return json_dict instead of json_string as json_string is of NSString type and not NSDictionary or NSArray.
and dont autorelease it, as it is your class variable
create method to fetchjson data.Pass your url in urlwithstring.
-(void)fetchjsondata
{
NSString *login= [[NSString stringWithFormat:#"your url string"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"----%#", login);
NSURL *url = [NSURL URLWithString:[login stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Get request and response though URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (data) {
dic_property= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%#", dic_property);
NSLog(#"counts=%d",[[dic_property objectForKey:#"Data"]count]);
}
else {
NSLog(#"network error, %#", [error localizedFailureReason]);
}
});
}];
}
call fetchjsonmethod in anywhere.
[NSThread detachNewThreadSelector:#selector(fetchdata) toTarget:self withObject:nil];

Resources