how to pass data from UIWebview to user defaults or another view - iphone-sdk-3.0

I have a embedded uiwebview in my app which will in turn call a webpage. This webpage contains some data which should be saved in the user defaults of the iphone. How to achieve this ?

It very much depends on what your page and data looks like... The basic approach is to use -stringByEvaluatingJavaScriptFromString: to retrieve content, e.g.:
NSString *script = #"document.getElementById('myTextInput').value";
NSString *result = [webView stringByEvaluatingJavaScriptFromString:script];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
result, #"MyTextInputValue",
// ... more?
nil];
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:#"MyWebViewData"];
If the data is only used by scripts in the page, you could also simply use a script function that returns you one JSON string to store:
NSString *script = #"window.getJsonData()";
NSString *json = [webView stringByEvaluatingJavaScriptFromString:script];

Related

modifying json data in a local file using SBjson

I have recently started Application development on MAC OS 10.6, I am trying to modify a "key/value" pair in a local JSON file on my MAC machine using SBJSON. I have successfully read the value of a key, but I am not able to get that how to modify the value of a key and synchronize this to the JSON file. Lets suppose, I have a following JSON Data int o a local file:
{
"name": {
"fName":"John",
"lName":"Doe"
}
}
And i want to change the value of "fName" to something else, like Robert.
I have tried alot searching about it, but got no clue... Can anyone help me.
I am using SBJSON Framework!
Code:
NSString *filePath = #"/Users/dev/Desktop/SQLiteFile/myJSON2.json";
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSString *responseString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSLog(#"FILE CONTENT : %#", responseString);
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSDictionary * dictionary = (NSDictionary*)[jsonParser objectWithString:responseString error:NULL];
[dictionary setObject:#"Robert" forKey:#"fName"];
//
// Code for writing this change into the file, which i needed.
//
[jsonParser release];
You want a mutable deep copy of your dictionary. Then you'll be able to modify it.

Multithreading to download data from a website

I'm doing an app which downloads info via a request to a website, giving me back and HTML and parsing this data I obtain my app info. For downloading this data I'm using, using a url with all the parameters the request needs at the end.
NSData *data = [NSData dataWithContentsOfURL:url];
NSString* htmlString;
htmlString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[self parserHTML:htmlString]; // here I fill a NSArray with the info parsed
[self searchSomething:htmlString]; // continue filling the NSArray
...
The task for download the data and parser the HTML takes long time.
What can I do to make this faster? Grand Central Dispatch? If so, how can I use it, because I'm using this and it doesn't works, because the NSSArray is empty:
dispatch_queue_t downloadQueue = dispatch_queue_create("pharmacy downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:urlReal];
NSString* htmlString;
htmlString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[self parserHTML:htmlString]; // here I fill a NSArray with the info parsed
[self searchSomething:htmlString]; // continue filling the NSArray
});
dispatch_release(downloadQueue);
If I don't use GCD it works. What can be the problem??
Thanks for your help. I'm totally lost!!! :S
Use NSURLDownload or NSURLConnection instead.
For some sample code you may take a look at QuickLookDownloader

how to make a small transparent modal overal to signify loading data?

I'm sure this has been asked before, but I've had no luck finding it. In my app data is loading synchronously, which locks up the app. I've tried asynch loading, but that doesn't work with the JSON parser.
To denote that the app isn't frozen, just working on downloading data, I was hoping to present the user with a small transparent overlay with the loading icon. I was wondering how to go about this - do I need to put it on another thread?
To clarify, I want to do something very similar to the Netflix iPad app - their loading overlay is perfect for the projet I'm working on.
Edit: I've added some async code below
I first call this function:
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSURLConnection *c = [[NSURLConnection alloc] init];
[self connectionWorks:c didReceiveData:data];
connectionworks
-(void)connectionWorks:(NSURLConnection *)connection didReceiveData:(NSData *)data{
OLWork *newWork;
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue];
NSArray *rawBooks = [results objectForKey:#"works"];
for (NSDictionary *work in rawBooks) {
newWork = [[OLWork alloc] init];
newWork.title = [work objectForKey:#"title"];
newWork.author = [[[work objectForKey:#"authors"] objectAtIndex:0] objectForKey:#"name"];
newWork.key = [work objectForKey:#"key"];
[self.works setValue:newWork forKey:newWork.title];
}
}
This will do the job for you, it's well documented and easy to use
https://github.com/jdg/MBProgressHUD
Out of intrest which JSON parser are you using? Getting asynchronous requests working would be a much better solution.

Change from a NSMutableArray to a .plist

I have been working through several tutorials on uitableviews.
I have put, as instructed, all the info into a 'listofitems' as below
listOfItems = [[NSMutableArray alloc] init];
NSArray *countriesToLiveInArray = [NSArray arrayWithObjects:#"Iceland", #"Greenland", #"Switzerland", #"Norway", #"New Zealand", #"Greece", #"Rome", #"Ireland", nil];
NSDictionary *countriesToLiveInDict = [NSDictionary dictionaryWithObject:countriesToLiveInArray forKey:#"Countries"];
NSArray *countriesLivedInArray = [NSArray arrayWithObjects:#"India", #"U.S.A", nil];
NSDictionary *countriesLivedInDict = [NSDictionary dictionaryWithObject:countriesLivedInArray forKey:#"Countries"];
[listOfItems addObject:countriesToLiveInDict];
[listOfItems addObject:countriesLivedInDict];
This creates a sectioned table view. I would like to know how to change it into a .plist instead of typing it all out into the RootViewController.m. I would still like it to be in a sectioned tableview.
Is there a simple method for changing from this NSMutableArray,NSArray and NSDictionary to a plist?
There's a simple method for this writeToFile:atomically::
[listOfItems writeToFile:destinationPath atomically:YES];
This will automatically create a file with plist inside it.
that sorta depends on what you want in a plist, and what you put into it. if the entries and contents are all CFPropertyList types (CFString,CFDate,CFData,CFDictionary,CFArray,CFNumber...) then just create it with something like CFPropertyListCreateDeepCopy.
if you have non-convertible custom objects (e.g., your own NSObject subclasses), then see the cocoa archiving topics.
This is the simple function end hear relization
This is function is updating NSArray
- (void) WriteRecordToFile:(NSMutableDictionary*)countDict {
// Here to write to file
databasePathCallCount = #"plist path";
NSMutableArray *countArray = [NSMutableArray arrayWithContentsOfFile:databasePathCallCount];
if(countArray)
[countArray addObject:countDict];
[countArray writeToFile:databasePathCallCount atomically:NO];
}

Object-c/iOS :About use NSUserDefaults set serial numbers/password

I got many issues about setting sn/pwd
Because the first default data is from URL
got a plist data like this:
{
serial_number=1234;
password = 7777;
}
The application finish launched,It will download from URL via the code like this
NSString *urlString = [[NSString alloc]initWithString:#"http://getdefaults.php"];
NSArray *plistData;
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURLURLWithString:urlString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
NSString *listFile = [[NSString alloc] initWithData:returnDataencoding:NSUTF8StringEncoding];
[listFile dataUsingEncoding:NSUTF8StringEncoding];
plistData = [listFile propertyList];
At first , I try to create a plist data in iphone:
NSArray *localPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *localDocPath = [localPaths objectAtIndex:0];
NSString *localFilePath = [localDocPath stringByAppendingPathComponent:#"InputPassword.plist"];
NSMutableDictionary *localDictread = [[NSMutableDictionary alloc] initWithContentsOfFile:localFilePath];
Than I compare with the information I get
if(localDictread==nil){
//pop a textfield to let user enter the serial numbers and password
//if the text in the textfield is equal the default SN/PWD from plistData,write the sn/pwd to plist in iphone
}
But I found NSUserDefaults , Can it work as the same ?
I mean work as the same is can I record a serial number and password in my iphone ???
What is best way to record a user serial number/password in iphone ?
If you are a storing password, not NSUserDefaults nor serializing the data in NSDocumentDirectory are great solutions because data is stored with little protection. iOS provides the KeyChain mechanism for this porupose. It provides C interfaces that are a bit obscure, but a Buzz Andersen got a nice Objective-C interface going called SFHFKeychainUtils. With SFHFKeychainUtils you can do something like:
[SFHFKeychainUtils storeUsername:user.text andPassword:pass.text forServiceName:#"my_service" updateExisting:YES error:nil];
And that gets stored securely into the keychain. To recover the password:
NSString *pw = [SFHFKeychainUtils getPasswordForUsername:user.text andServiceName:#"my_service"