NSDictionary dictionaryWithObject issue - ios

I'm trying to get Title data from the server but unfortunately I'm getting nothing as it is shown in the NSLog below. Shouldn't I get the Title dictionary? Please where would be my issue?
While I want to set that data in the UITableVeiw
- (void)getNews{
NSURL *url = [NSURL URLWithString:#"http://www.example.ashx"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *getData = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
if([[[getData objectForKey:#"Success"] stringValue] isEqualToString:#"1"]){
[dataNewsArray addObjectsFromArray:[[greeting objectForKey:#"Response"] objectForKey:#"Datasource"]];
}
NSDictionary *aDict = [NSDictionary dictionaryWithObject:dataHaberlerArray forKey:#"Title"];
NSLog(#"Check %#", aDict);
}
}];
}
NSLog result as like this;
Check {
Title = (
{
Content = "";
Date = "13.10.2014";
Time = "01:17:34";
Title = "example";
},
NSLog for dataNewsArray
2014-10-13 13:40:14.828 new_8[8742:346345] Check (
{
Content = " ";
Date = "13.10.2014";
Time = "01:38:53";
Title = "*test*";
},

write the below code to get one title
[[[aDict objectForKey:#"Title"] objectAtIndex:0] objectForKey:#"Title"]];
for all the titles use the below code
NSMutableArray *titleArray = [[NSMutableArray alloc] init];
for (int i=0; i<[[aDict objectForKey:#"Title"] count]; i++) {
[titleArray addObject:[[[aDict objectForKey:#"Title"] objectAtIndex:i] objectForKey:#"Title"]];
}
The above solution provide the answer, but there is some other way using predicate to get the data

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 do i create my array dynamically where values fetching from json in ios

-(IBAction)DropDownPressed:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://rest-service.guides.spring.io/greeting"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSArray * array = [greeting objectForKey:#"id"];
NSLog(# "%#",array);
ibtn=0;
[Dropobj fadeOut];
[self showPopUpWithTitle:#"Select Country" withOption:arryList xy:CGPointMake(16, 58) size:CGSizeMake(287, 330) isMultiple:NO];
}
}
];
}
- (void)viewDidLoad {
[super viewDidLoad];
arryList=[[NSArray alloc] initWithObjects:#"india",#"pakistan",nil ];
}
#interface ViewController : UIViewController<kDropDownListViewDelegate>{
NSArray *arryList;
int ibtn;
}
this is my interface file
i wish to create a arraylist like arryList in the viewdidload method..i fetch the json values from restapi call and convert those into arrays...those values i get from the restapi call have to be loaded dynamically...how to do it....please suggest me ideas....
You can do it by the following way.
#interface MasterViewController ()
#property NSMutableArray *arryList;
#end
#implementation MasterViewController
#synthesize arryList;
- (void)viewDidLoad {
[super viewDidLoad];
int totalData = 10;
arryList=[[NSMutableArray alloc] initWithCapacity:totalData];
for (int i=0; i<totalData; i++) {
[arryList addObject:#""];
}
}
-(IBAction)DropDownPressed:(id)sender{
UIButton *button = (UIButton*)sender;
NSLog(#"tag:%d",button.tag);
id currentValue = [arryList objectAtIndex:button.tag];
if ([currentValue isKindOfClass:[NSString class]] && [(NSString*)currentValue isEqualToString:#""]) {
NSDictionary *dataDictionary = [[NSDictionary alloc] init];
[self getURLResponse:&dataDictionary];
NSString *myID = [dataDictionary objectForKey:#"id"];
NSString *content = [dataDictionary objectForKey:#"content"];
[arryList replaceObjectAtIndex:button.tag withObject:myID];
NSLog(#"arryList:%#",arryList);
}else{
NSLog(#"already downloaded");
}
}
-(void)getURLResponse:(NSDictionary**)dataDictionary{
NSURL *url = [NSURL URLWithString:#"http://rest-service.guides.spring.io/greeting"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:
request returningResponse:&response error:&error];
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
// ibtn=0;
// [Dropobj fadeOut];
// [self showPopUpWithTitle:#"Select Country" withOption:arryList xy:CGPointMake(16, 58) size:CGSizeMake(287, 330) isMultiple:NO];
*dataDictionary = [[NSDictionary alloc]initWithDictionary:greeting copyItems:YES];
}

Is it possible to only get a url title without load whole wabpage?

I know that use a UIWebview can get title in delegate method webViewDidFinishLoad
But,I want to know if there is a way to only get the title without load the whole webpage?Like http request or something else?
Create url request with asynchronous call to get data from url.
This can be done like this for example:
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
^(NSURLResponse *response, NSData *data, NSError *err) {
// Get Title
NSString *strTitle = #"";
if (data && !err)
{
NSString *returnDataIntoString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(#"data : %#",returnDataIntoString);
if (returnDataIntoString.length > 0)
{
NSError *error = nil;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithHTMLString:returnDataIntoString encoding:NSUTF8StringEncoding error:&error];
if (doc && !error) {
NSArray *employees = [doc nodesForXPath:#"//title" error:NULL];
for (GDataXMLElement *employe in employees) {
strTitle = [employe stringValue];
}
}
}
}
else
{
NSLog(#"Error : %#",[err description]);
}
//Set Title here
}];
Note : Now i have used third party library to parse html using GDataXML-HTML
Do you have a whole HTML string? You can using regular expression to parse string if you have it:
NSString *string = #"Your HTML String";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"<title[^>]*>(.*?)</title>"
options:0
error:&error];
NSTextCheckingResult *result = [regex firstMatchInString:string options:NSMatchingReportProgress range:NSMakeRange(0, [string length])];
NSRange titleRange = [result rangeAtIndex:1];
NSString *title = [string substringWithRange:titleRange];

How to use asynchronous data

I'm trying to fetch some data from a remote file. I'm creating an _items array inside the asynchronous request block, which is actually full of data, but when calling the _items anywhere else in my controller is still empty.
I'm not sure but i'm guessing that as the data are loaded asyncronously, when calling _items is still empty. So how how can i use the array with data, after the async task is completed?
- (IBAction)fetchEvent
{
_items = [[NSMutableArray alloc] initWithCapacity:5];
NSString *link = [NSString stringWithFormat:#"url...?id=%#", self.eId];
NSURL *url = [NSURL URLWithString:link];
NSURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *match = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSArray *odds = [match objectForKey:#"odds"];
OddsItem *item;
for ( NSDictionary *books in odds ) {
item = [[OddsItem alloc] init];
item.oddsBook = [odds objectForKey:#"book"];
[_items addObject:item];
}
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchEvent];
}
mutable data is dangerous in multi thread situation. NSArray is better.
#property (nonatomic, copy) NSArray *items;
block can capture outside variables but can not modify it directly. In completion block try this
if (data.length > 0 && connectionError == nil)
{
NSDictionary *match = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSArray *odds = [match objectForKey:#"odds"];
NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:5];
for ( NSDictionary *books in odds ) {
OddsItem *item = [[OddsItem alloc] init];
item.oddsBook = [odds objectForKey:#"book"];
[items addObject:item];
}
self.items = items;
}

How we get data from server using the JSON query?

**In this code When add breakpoint from viewdidload( ) function then i got greetingArray.count zero but when i add breakpoint at the for loop then it works properly and i got the results 3 as the values of the greetingArray. What is the possible reason that no getting the data from server.There is no problem with server side.I already check for it.
- (void)viewDidLoad
{
[super viewDidLoad];
greetingArray = [[NSMutableArray alloc] init];
greetingDictionary = [[NSMutableDictionary alloc] init];
NSString *connectionString;
connectionString=[NSString stringWithFormat:#"http://xxx.xxx.x.xx/TestMgt/api/%#",self.fieldName];
NSURL *url = [NSURL URLWithString:connectionString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSLog(#"----------------------------------------------------");
NSLog(#"Data length is = %d",data.length);
greetingMArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(#"%#",greetingMArray);
for(int i = 0 ; i< greetingMArray.count; i++)
{
greetingDictionary = (NSMutableDictionary *)[greetingMArray objectAtIndex:i];
NSLog(#"%#",greetingDictionary);
ConnectionOvertime *overtime = [[ConnectionOvertime alloc] init];
overtime.entryDate=[greetingDictionary valueForKey:#"EntryDate"];
[greetingArray addObject:overtime];
NSLog(#"%d",greetingArray.count);
}
}
}];
}
if you don't get any answer try jsonFramework library and import sbjsonParser.h
for Example try below code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.ChapterID=[[NSMutableArray alloc]init];
self.ChapterName=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"https://www.coursekart.com/webservice/load-subjects.php?api_key=68410920GHJFLAC878&standard_id=2&format=json"];
NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url];
NSError *error;
NSURLResponse *response;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(data!=nil)
{
NSString *content=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(content.length!=0)
{
SBJsonParser *parser=[[SBJsonParser alloc]init];
NSArray *dir=[[parser objectWithString:content]objectForKey:#"SubjectList"];
for(int i=0;i<dir.count;i++)
{
NSDictionary *array=[dir objectAtIndex:i];
NSArray *data=[array objectForKey:#"Data"];
NSDictionary *dat=(NSDictionary *)data;
NSString *idCh=[dat objectForKey:#"id"];
NSString *slug=[dat objectForKey:#"slug"];
[ChapterID addObject:idCh];
[ChapterName addObject:slug];
// NSLog(#"%#",[ChapterID objectAtIndex:0]);
//NSLog(#"%#",[ChapterName objectAtIndex:0]);
}
}
}
}

Resources