I am loading data from server which is working fine without problem and I can see res value in the NSLog as
2013-11-19 16:22:48.799 Paaa[4278:a0b] res ( { "choice_name" = "DATA0"; }, { "choice_name" = "DATA1"; }, { "choice_name" = "DATA2"; } )The problem is I can't view it in the `pickerView` It always indicate to `return [res count]` as EXC_BAD_ACCESS. So please where would be my problem?
.H:
#property (nonatomic, strong) NSMutableArray *res;
.M:
- (void)requestPos:(ASIFormDataRequest *)request{
NSData *responseData = [request responseData];
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// Create a dictionary from the JSON string
NSDictionary *result = [jsonString JSONValue];
[jsonString release];
CXMLDocument *doc = [[[CXMLDocument alloc] initWithXMLString:[result objectForKey:#"Response"] options:0 error:nil] autorelease];
NSArray *nodes = [doc nodesForXPath:#"/root" error:nil];
NSArray *nodes3 = NULL;
nodes3 = [doc nodesForXPath:#"/root/cl_choicelist/cl_choice" error:nil];
NSLog(#"node3%#", nodes3);
// we will put parsed data in an a array
res = [[NSMutableArray alloc] init];
for (CXMLElement *node in nodes3) {
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
int counter;
for(counter = 0; counter < [node childCount]; counter++) {
// common procedure: dictionary with keys/values from XML node
[item setObject:[[node childAtIndex:counter] stringValue] forKey:[[node childAtIndex:counter] name]];
}
// and here it is - attributeForName! Simple as that.
[item setObject:[[node attributeForName:#"choice_name"] stringValue] forKey:#"choice_name"]; // <------ this magical arrow is pointing to the area of interest.
[res addObject:item];
[item release];
}
NSLog(#"res %#", res);
[res release];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [res count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [[res objectAtIndex:row]objectForKey:#"choice_name"];
}
- (IBAction)openPickerView{
[actionSheet showInView:self.view];
[UIView beginAnimations:nil context:nil];
[actionSheet setBounds:CGRectMake(0, 0, 320, 492)];
[UIView commitAnimations];
}
Don't release res at the end of requestPos:
If Bhumeshwer katre won't write his answer, then I will :)
Related
The feed in question is https://fritchcoc.podbean.com/feed/
I have this in my code to parse, but every time I run it, I get an error message of the following. I have tried to add exception breakpoints, but it is not showing me the line of code causing all the commotion. I have spent two hours on this with no luck at all figuring out the issue. I set every NSString to nil within the commands, just in case one of the item valueForChild was coming up with errors, but even with all nils, they had issues.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[RSSEntry initWithBlogTitle:articleTitle:articleUrl:articleDate:articleImage:contentEncoded:]: unrecognized selector sent to instance
- (void)viewDidLoad {
[super viewDidLoad];
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:#"https://fritchcoc.podbean.com/feed/",
nil];
[self refresh];
}
- (void)refresh {
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
[self parseAtom:rootElement entries:entries];
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(#"Failed to parse %#", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//int newCounter = 0;
for (RSSEntry *entry in entries) {
// newCounter++;
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:nil];
/* if (newCounter > 999) {
break;
}*/
}
}];
}
}];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"Error: %#", error);
[self refresh];
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSLog(#"Go");
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSString *theCategory = [item valueForChild:#"category"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
NSString *articleUrl = [[[[item elementsForName: #"enclosure"] lastObject] attributeForName: #"url"] stringValue];
NSString *picture = [[[[item elementsForName: #"media:content"] lastObject] attributeForName: #"href"] stringValue];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate
articleImage:picture
contentEncoded:nil
category:theCategory] autorelease];
if ([theCategory isEqualToString:#"Sermon"]) {
[entries addObject:entry];
}
}
}
}
In your code you have this call:
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate
articleImage:picture
contentEncoded:nil
category:theCategory] autorelease];
It has a "category" last parameter, but your error message doesn't have it:
Terminating app due to uncaught exception
'NSInvalidArgumentException',
reason: '-[RSSEntry initWithBlogTitle:articleTitle:articleUrl:articleDate:articleImage:contentEncoded:]:
unrecognized selector sent to instance
Is it possible that you have made a new version of RSSEntry that has "category", but didn't recompile properly some of your parsing code, and that code is still trying to call an old method (without "category")?
If so, just do a Product - "Clean" - "Build", and pay attention to compilation errors an warnings.
I've noticed that you still are not using ARC (calling "autorelease"), which indicates to me that it's a really old code :)
I need to display particular object for key(currency) using post method after getting response from web.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController{
NSMutableData *mutableData;
NSMutableString *arr;
#define URL #"website"
// change this URL
#define NO_CONNECTION #"No Connection"
#define NO_VALUES #"Please enter parameter values"
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)sendDataUsingPost:(id)sender{
[self sendDataToServer :#"POST"];
}
-(IBAction)sendDataUsingGet:(id)sender{
[self sendDataToServer : #"GET"];
}
-(void) sendDataToServer : (NSString *) method{
NSString *Branchid=#"3";
serverResponse.text = #"Getting response from server...";
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
NSLog(#"responseData: %#", arr);
//NSLog(#"%#",[[arr valueForKey:#"BranchByList"]objectForKey:#"currency"]);
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
if( connection )
{
mutableData = [NSMutableData new];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
[mutableData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
serverResponse.text = NO_CONNECTION;
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableString *responseStringWithEncoded = [[NSMutableString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
//NSLog(#"Response from Server : %#", responseStringWithEncoded);
NSLog(#"%#",responseStringWithEncoded );
NSLog(#"%#",[responseStringWithEncoded valueForKeyPath:#"BranchByList.currency"] );
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
serverResponse.attributedText = attrStr;
// NSLog(#"%#",attrStr);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
i got response branch_id=3 but i want to show to "currency" but i tried lot but failure.
my response like this I need to display only currency.....
Response from Server :
{"BranchByList":
[
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newantara\/images\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
},
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newantara\/images\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
}
]};
Your response structure is:
-Dictionary
--Array
---Dictionary Objects
You need to convert your Data into NSDictionary to parse it.
Following code will do that for you:
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error]; //Now we got top level dictionary
NSArray* responseArray = [json objectForKey:#"BranchByList"]; //Now we got mid level response array
//Get Embeded objects from response Array:
NSDictionary *priceDic = [responseArray objectAtIndex:0]; //Getting first object since you arent telling what the second object is for
NSString *buyingPrice = [priceDic objectForKey: #"buy"]; //Buying price
NSString *sellingPrice = [priceDic objectForKey:#"sell"]; //Selling price
NSString *currency = [priceDic objectForKey:#"currency"]; //Currency
Though this is only sticking to the point and getting the job done.
Proper way to get the job done would be to create a model class for response. Create a class inherited from NSObject and use it as model for this response. Add a initWithDic: method to that class, Pass it your response dic as parameter and delegate all this dictionary parsing to that method.
Also, NSURLConnection is deprecated since iOS 9.0. You should use NSURLSession instead.
Try This May be it will help you:-
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMArray *array1 = [dict6 objectForKey:#"BranchByList"];
NSLog(#"DICT : %#",array1);
NSDictionary *Dict3 = [array1 objectAtIndex:0];
NSString *Str1 = [dict3 objectForKey:#"currency"];
NSLog(#"Str1 : %#",Str1);
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
} else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
} else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
} else
{
return jsonObject;
}
}
I am trying to make a nsurl request and manage to retrieve the web response data out. The problem is i want to retrieve the specific parameter from the JSON list. The parameter i want to retrieve is "id" and display it out in a label.
Here is my viewDIDLoad for establishing the connection:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
feeds = [[NSMutableArray alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://coolsoft.mousy.com/v1/messi/reports"]];
// Prepare the variables for the JSON response
// Create a mutable copy of the immutable request and add more headers
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[mutableRequest addValue:#"application/json" forHTTPHeaderField:#"request"];
// Make synchronous request
request = [mutableRequest copy];
// Log the output to make sure our new headers are there
NSLog(#"%#", request.allHTTPHeaderFields);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
if(connection)
{
_webResponseData = [NSMutableData data] ;
}
else
{
NSLog(#"Connection is NULL");
}
}
His is my connectionDidFinishLoading method:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Received %lu Bytes", (unsigned long)[_webResponseData length]);
// NSString *theXML = [[NSString alloc] initWithBytes:
// [_webResponseData mutableBytes] length:[_webResponseData length] encoding:NSUTF8StringEncoding];
// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];
NSString *icon;
// show all values
for(id key in res) {
id value = [res objectForKey:key];
NSString *keyAsString = (NSString *)key;
NSString *valueAsString = (NSString *)value;
NSLog(#"key: %#", keyAsString);
NSLog(#"value: %#", valueAsString);
}
// extract specific value...
NSArray *results = [res objectForKey:#"id"];
for (NSDictionary *result in results) {
icon = [result objectForKey:#"id"];
NSLog(#"icon: %#", icon);
}
output.text = icon;
output = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 100)]; //adjust label size and position as needed
output.font = [UIFont fontWithName:#"BradleyHandITCTT-Bold" size: 23.0];
output.textColor = [UIColor whiteColor];
output.textAlignment = NSTextAlignmentCenter;
output.numberOfLines = 0; //note: I said number of lines need to be 2
output.backgroundColor = [UIColor clearColor];
output.adjustsFontSizeToFitWidth = YES;
output.tag = 100;
}
Here is output when i NSLOG the res dictionary:
( { date = "2014-08-28T00:00:00Z"; id = 300005; title = "July 2014 USAA Phishing Campaign Uses KeNiHaCk Exploit"; uri = "/v1/joker/reports/300005"; }, { date = "2014-12-16T20:46:29Z"; id = 300062; title = "Two-Year Chinese Spearphishing Campaign Largely Targeted Japanese Aerospace and Energy Industries"; uri = "/v1/joker/reports/300062"; },
Here is my error message:
-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x136713360
2015-12-30 11:58:17.692 FYP_IOS_APP[817:323807] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x136713360'
Your JSON response is {"id":300005,"title":"pink","date":"2014-08-28T00:00:00Z","uri":"www.hipster.com/hip"}}
So, You can use like, lblName.text = [res valueForKey:#"id"];
Your json parsing is OK and it gives you JSON to NSDictionary
but you need some minor changes in pasing that NSDictionary object as below.
see this below code & It may help you
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
//{"id":300005, "title":"pink", "date":"2014-08-28T00:00:00Z", "uri":"www.hipster.com/hip"}
NSLog(#"Received %lu Bytes", (unsigned long)[_webResponseData length]);
// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];
NSString *icon;
// show all values
for(id key in [res allKeys]) {
NSLog(#"key: %#", key);
NSLog(#"value: %#", [res objectForKey:key]);
}
// extract specific value...
icon = [res valueForKey:#"id"];
NSLog(#"icon: %#", icon);
output.text = icon;
output = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 100)]; //adjust label size and position as needed
output.font = [UIFont fontWithName:#"BradleyHandITCTT-Bold" size: 23.0];
output.textColor = [UIColor whiteColor];
output.textAlignment = NSTextAlignmentCenter;
output.numberOfLines = 0; //note: I said number of lines need to be 2
output.backgroundColor = [UIColor clearColor];
output.adjustsFontSizeToFitWidth = YES;
output.tag = 100;
}
update
// convert to JSON
NSError *myError = nil;
NSArray *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];
// show all values
for(NSDictionary *dic in res) {
for(NSString *key in [dic allKeys]) {
NSLog(#"key: %#", key);
NSLog(#"value: %#", [dic objectForKey:key]);
}
}
I have one login screen after that it will move to next view controller which have i have used some networks like http,json to get data from server. when i enter login username/password then if i click login button its getting delay to 8 seconds after that only it moving to next view controller.Still that my login screen alone showing for 8 seconds and then only it move to next view controller.
Here my login controller.m:
#implementation mainViewController
- (void)viewDidLoad {
[super viewDidLoad];
_username.delegate = self;
_password.delegate = self;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:#"reg"]) {
NSLog(#"no user reg");
_logBtn.hidden = NO;
}
}
- (void)viewWillAppear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:YES animated:animated];
[super viewWillAppear:animated];
_username.text = nil;
_password.text = nil;
}
- (IBAction)LoginUser:(id)sender {
if ([_username.text isEqualToString:#"sat"] && [_password.text isEqualToString:#"123"]) {
NSLog(#"Login success");
[self performSegueWithIdentifier:#"nextscreen" sender:self];
}
else {
NSLog(#"login was unsucess");
// Alert message
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"wrong"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil];
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
}
Here my nextcontroller.m
- (void)viewDidLoad {
[super viewDidLoad];
//for search label data
self.dataSourceForSearchResult = [NSArray new];
//collection of array to store value
titleArray = [NSMutableArray array];
// here only i am getting data from server
[self getdata];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView reloadData];
}
Help me out. If my question din't understand.I can tell more about my post. And in my nextcontroller.m [self getdata] is i am getting data from server url.Thanks
My get data:
-(void)getdata {
NSString *userName = #“users”;
NSString *password = #“images”;
NSData *plainData = [password dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
base64String=[self sha256HashFor: base64String];
NSString *urlString = #"https://porterblog/image/file”;
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", userName, base64String];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError * error;
self->arrayPDFName = [[NSMutableArray alloc]init];
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dictOriginal = jsonResults[#“birds”];
[titleArray addObject:[NSString stringWithFormat:#" birds(%#)”, dictOriginal[#"count"]]];
NSDictionary *dictOriginal2 = jsonResults[#"owl”];
[titleArray addObject:[NSString stringWithFormat:#" Owl(%#)”, dictOriginal2[#"count"]]];
NSDictionary *dictOriginal3 = jsonResults[#"pensq”];
[titleArray addObject:[NSString stringWithFormat:#" Pensq(%#)”, dictOriginal3[#"count"]]];
NSDictionary *dictOriginal4 = jsonResults[#“lion”];
[titleArray addObject:[NSString stringWithFormat:#" lion(%#)”, dictOriginal4[#"count"]]];
NSArray *arrayFiles = [NSArray arrayWithObjects: dictOriginal, dictOriginal2, dictOriginal3, dictOriginal4, nil];
NSLog(#"str: %#", titleArray);
for (NSDictionary *dict in arrayFiles) {
NSMutableArray *arr = [NSMutableArray array];
NSArray *a = dict[#"files"];
for(int i=0; i < a.count; i ++) {
NSString *strName = [NSString stringWithFormat:#"%#",[[dict[#"files"] objectAtIndex:i] valueForKey:#"name"]];
[arr addObject:strName];
}
[arrayPDFName addObject:arr];
}
NSString *errorDesc;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory1 stringByAppendingPathComponent:#"SampleData.plist"];
NSString *error1;
returnData = [ NSPropertyListSerialization dataWithPropertyList:jsonResults format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
if(returnData ) {
if ([returnData writeToFile:plistPath atomically:YES]) {
NSLog(#"Data successfully saved.");
}else {
NSLog(#"Did not managed to save NSData.");
}
}
else {
NSLog(#"%#",errorDesc);
}
NSDictionary *stringsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
}
EDITED:
`- (void)viewDidLoad {
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
self.dataSourceForSearchResult = [NSArray new];
titleArray = [NSMutableArray array];
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView reloadData];
self.navigationItem.hidesBackButton = YES;
});
});
}`
You're getting your data using main thread you need do to that in background then invoke the code you need (as i see is reload collectionView)
I assume that because you didn't show the getdata method code
If that the case you can use this code:
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
[self.collectionView reloadData];
});
});
It's mean that your VC will show immediately but the collectionView fill after you finish load the data, you can put some old data while loading like Facebook app (you see latest retrieved posts until finish loading].
Edit:
In your code you replace viewdidload method in nextController with next code:
- (void)viewDidLoad {
[super viewDidLoad];
//for search label data
self.dataSourceForSearchResult = [NSArray new];
//collection of array to store value
titleArray = [NSMutableArray array];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
[self.collectionView reloadData];
});
});
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
}
I create one application and I read many data in table View from JSON and I want parsed this JSON and store in sqlite but I dont know from where should I start?
this is parsed my json code :
#implementation TableViewController
{
NSArray *news;
NSMutableData *data;
NSString *title;
NSMutableArray *all;
}
#synthesize mainTable;
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"News";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://zacandcatie.com/YouTube/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[con start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
news = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
for (int i =0; i < [news count]; i++)
{
NSIndexPath *indexPath = [self.mainTable indexPathForSelectedRow];
title =[[news objectAtIndex:indexPath.row+i]objectForKey:#"title"];
if (!all) {
all = [NSMutableArray array];
}
[all addObject:title];
}
NSLog(#"%#",all);
[mainTable reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"The Connection has been LOST" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
you my json url. I want store "title"&"date_string" value in sqlite.
please guide me!!!
After parsing you data in the form of NSDictionary you can create a query of insert into and fire the query n your data will be save into your database
-(void)InsertRecords:(NSMutableDictionary *)dict
{
sqlite3_stmt *stmt;
sqlite3 *cruddb;
NSMutableString *str = [NSMutableString stringWithFormat:#"Insert into tblName ("];
for (int i = 0; i<[[dict allKeys] count]; i++)
{
[str appendFormat:#"%#,",[[dict allKeys] objectAtIndex:i]];
}
[str appendFormat:#")values ("];
for (int i = 0; i<[[dict allKeys] count]; i++)
{
[str appendFormat:#"%#,",[dict valueForKey:[[dict allKeys] objectAtIndex:i]]];
}
[str appendFormat:#");"];
NSLog(#"qry : %#",str);
const char *sql = [str UTF8String]; ;
if((sqlite3_open([database UTF8String], &cruddb)==SQLITE_OK))
{
if (sqlite3_prepare(database, sql, -1, &stmt, NULL) ==SQLITE_OK)
{
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
else
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(database));
}
sqlite3_close(database);
}
else
{
NSLog(#"An error has occured: %s",sqlite3_errmsg(database));
}
}
Try this.
Continuing #Divz Ans...
you will have create the .sqlite file. And there is nothing easier than this.
There are two ways(that i know) to create sqlite file,
1> you can download SQLite Manager add-on in firefox, where you can manipulate data in database graphically.
Or,
2> you can use Terminal with a single line command, sqlite3 dbFileName.sqlite. enter,
where you will get sqlite> now start with further SQL(create/insert/update..) queries.
you can find your sqlite file at MacHD>users>admin(not shared one)>yourFile.sqlite or, finder---go>home>yourFile.sqlite
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
db=[[SKDatabase alloc]initWithFile:#"student.sqlite"];
NSURL *url=[NSURL URLWithString:#"..........Your Url............"];
NSURLRequest *json_request=[[NSURLRequest alloc]initWithURL:url];
NSData *data=[NSURLConnection sendSynchronousRequest:json_request returningResponse:nil error:nil];
NSMutableDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableArray *student_ary=[dic objectForKey:#"students"];
for (NSMutableArray *student_info in student_ary) {
NSMutableDictionary *insert=[[NSMutableDictionary alloc]initWithCapacity:2];
NSMutableDictionary *info=[student_info mutableCopy];
[insert setObject:[info objectForKey:#"name"] forKey:#"name"];
[insert setObject:[info objectForKey:#"city"] forKey:#"city"];
[db insertDictionary:insert forTable:#"student_info"];
}
})
//.m file view....
-(void)viewDidAppear:(BOOL)animated
{
NSString *qry=#"select * from student_info";
ary=[[db lookupAllForSQL:qry] mutableCopy];
[tableView reloadData];
}
You can do some thing like this :
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// tableview cell setup
NSArray* keys = [self.data allKeys];
cell.textLabel.text = [self.data objectForKey:[keys objectAtIndex:indexPath.row]];
return cell;
}
Please refer this links to have data in order in dictionary
NSDictionary with ordered keys