Load URL within JSON in UIWebView? - ios

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 ;)

Related

ios - update UI inside block

I make a call to the youtube API to get the title of a video. I then want to display the title of the video on the screen in a table. How do I access the title after the block has finished executing?
Here's the code to get the title
-(void)getVideoTitle:(NSString *)urlStr success:(void (^)(NSDictionary *responseDict))success{
urlStr = [NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/videos?part=contentDetails%%2C+snippet%%2C+statistics&id=%#&key={API_KEY}",urlStr];
NSURL *url = [[NSURL alloc] initWithString:urlStr];
// Create your request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// Send the request asynchronously
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) {
// Callback, parse the data and check for errors
if (data && !connectionError) {
NSError *jsonError;
NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
if (!jsonError) {
success(jsonResult);
// NSLog(#"Response from YouTube: %#", jsonResult);
}
}
}] resume];
}
Here's how I call the above function:
[self getVideoTitle:#"zB4I68XVPzQ" success:^(NSDictionary *responseDict){
NSArray *itemsArray = [responseDict valueForKey:#"items"];
NSDictionary *item = itemsArray[0];
NSDictionary* snippet = [item valueForKey:#"snippet"];
NSString *title = [snippet valueForKey:#"title"];
}];
How do I get access the title variable outside the block after the block has finished executing?
I have tried the following with no luck
dispatch_async(dispatch_get_main_queue(), ^{
[self updateMyUserInterfaceOrSomething];
});
In your code:
NSString* recievedTitle __block = nil; //title is here, after block below run
[self getVideoTitle:#"zB4I68XVPzQ" success:^(NSDictionary *responseDict){
NSArray *itemsArray = [responseDict valueForKey:#"items"];
NSDictionary *item = itemsArray[0];
NSDictionary* snippet = [item valueForKey:#"snippet"];
recievedTitle = [snippet valueForKey:#"title"]; //here you write it
// or
NSString *title = [snippet valueForKey:#"title"];
[self updateInterfaceWithTitle: title]
}];
///
- (void)updateInterfaceWithTitle:(NSString*)title{
//use title here
}

How to pass multiple parameters in URL to web View in 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]];
}

simple mantle JSON example from URL

I have have some trouble in understanding what is needed to fetch a JSON file with mantle.h from a URL.
Can someone give me an example of how it works?
For example:
-I have a URL www.example.com with a JSONFile as follows:
{
"name": "michael"
}
How could I fetch it?
I use this process for fetching JSON:
NSURL *s = url;//Put your desird url here
NSURLRequest *requestURL = [NSURLRequest requestWithURL:s cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.00];
NSHTTPURLResponse *response;
NSError *error = [[NSError alloc]init];
NSData *apiData = [NSURLConnection sendSynchronousRequest:requestURL returningResponse:&response error:&error];
dictionaryData = [NSJSONSerialization JSONObjectWithData:apiData options:kNilOptions error:&error];
Now the dictionaryData contains your JSON. You can fetch it by:
NSString *name = [dictionaryData valueForKey:#"name"];
And make sure you are making async request. For this put the code within this block:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
//Put the code here
});
Hope this helps.. :)
Call it with following method
[super getRequestDataWithURL:urlString
andRequestName:sometext];
You will get response in the following method if successful
- (void)successWithRequest:(AFHTTPRequestOperation *)operation withRespose:(id)responseObject withRequestName:(NSString *)requestName {
NSString *response = operation.responseString;
id jsonObject = [response objectFromJSONString];
if(![super checkforServerRequestFailureErrorMessage:jsonObject]) {
[self.leaderboardProxyDelegate leaderboardListSuccessful:jsonObject];
}
}
You will get dictionary in jsonObject

AFNetworking block and feed

Okay I have another question, tonight, using AFNetworking, i parse my JSON Stream, an add object an MutableArray, when i insert try to print the array outside of the success block, it says null, but inside of this block it works, so how can i pass the _listOfNewsArray into the mainthread ?
This is my code :
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"bgWhitelight" ofType:#"png"];
self.tableView.backgroundColor = [[UIColor alloc] initWithPatternImage:[[UIImage alloc] initWithContentsOfFile:path]];
NSURLRequest *newsRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://aXXXXXXXXXXXipt/beta.php"]];
AFJSONRequestOperation *newsJSONRequest = [AFJSONRequestOperation JSONRequestOperationWithRequest:newsRequest success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
NSArray *newsArray = [JSON objectForKey:#"news"];
_listOfNews = [[NSMutableArray alloc]init];
for (NSDictionary *oneNews in newsArray) {
CCENews *currentNews = [[CCENews alloc]init];
currentNews.title = [oneNews objectForKey:#"title"];
currentNews.content = [oneNews objectForKey:#"content"];
currentNews.category = [currentNews getHiResCategoryPicture:[oneNews objectForKey:#"category"]];
currentNews.date = [oneNews objectForKey:#"date"];
currentNews.imageURL = [oneNews objectForKey:#"pictureurl"];
[_listOfNews addObject:currentNews];
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"%#", error);
}];
[newsJSONRequest start];
In fact, i found the solution, just using self.listOfNews, just had to think about it !-
Move the creation of listOfNews out of the block and into viewDidLoad, or make the ivar a block variable (_block NSM....). I prefer the first solution.

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