How to download xml file and save in local iphone application - iphone

I have a magazine application i want that it load file from server and store it in application when application starts first time only and then use that locally file to save time i am getting data which is located on server it takes alot time
NSURL*myurl=url;
myurl = [myurl stringByReplacingOccurrencesOfString:#"\n" withString:#""];
myurl = [myurl stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSURL*urlloaded= [[NSURL alloc]initWithString:myurl];
//NSURL*url= [[NSURL alloc]initWithString:#"http://localhost:8888/RowOne.xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:urlloaded];
//Initialize the delegate.
RowTwoParser *parser = [[RowTwoParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
BOOL success = [xmlParser parse];
if(success)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");

What you can do is:-
Suppose you have parsed your xml and stored data in array say 'dataArray'
Now you have to save your dataArray in NSUserDefaults
NSUserDefaults *pref1=[NSUserDefaults standardUserDefaults];
[pref1 setObject:dataArray forKey:#"parseData"];
[pref1 synchronize];
Whenever you have to use this data you can extract it like:-
NSUserDefaults *pref1=[NSUserDefaults standardUserDefaults];
NSArray *dataArray=[pref1 objectForKey:#"parseData"];

You can download the initial data i.e the XML file by using something like this
- (void)downloadInitialData {
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
if ([userDefaults boolForKey:#"DATA_DOWNLOAD_KEY"] == NO) {
[self showWaitViewWithText:#"Downloading Data..."];
[self fetchDataFromServer];
}
}
- (void)fetchDataFromServer {
//Call to server to downlaod data
//When Data is successfully downloaded
//Stop loading when data save completes
[self stopLoading];
//Update USerDefaults
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:YES forKey:#"DATA_DOWNLOAD_KEY"];
[userDefaults synchronize];
}
You can make call to [self downloadInitialData]; which will ensure that Data is downloaded only once when the application starts . You will have to fix it according to your requirements to download data by resetting the #"DATA_DOWNLOAD_KEY" key.

Check out Apples own SeismicXML example - source code available.

Related

Unable to retrieve NSMutableArray from NSUserDefaults

I have an issue persisting data in local storage for an NSMutableArray containing a list of NSStrings.
I have a save method and a get method both appear to work when the app is running. However, once I close the app and restart the items in the array are gone.
NSMutableArray*ImageTags;
Get Data
-(NSMutableArray*)GetDataNSMutableArray:(NSString*)ItemName
{
NSMutableArray *GetData = [[NSMutableArray alloc] init];
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:ItemName];
if (dataRepresentingSavedArray != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
GetData = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
GetData = [[NSMutableArray alloc] init];
}
return GetData;
}
Save Data
-(void)SaveDataNSMutableArray:(NSString*)ItemName:(NSMutableArray*)Data
{
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:Data] forKey:ItemName];
}
How items are added
[ImageTags addObject:Control.titleLabel.text]
How array is saved
[super SaveDataNSMutableArray:CVC_ImageURL:ImageTags];
How array is retrieved
ImageTags = [super GetDataNSMutableArray:CVC_ImageURL];
NSUserDefaults always return immutable instances.
Unrelated:
(Conventions says that methodNames should always begin with a small letter).
[[NSUserDefaults standardUserDefaults] synchronize]
To dump all the contents from NSUserDefaults onto persistent store
Your can not store mutable array to user defaults. Store the immutable copy and retrieve that and convert to mutable ones to access during the next launch.
You can do synchronization while saving:
-(void)SaveDataNSMutableArray:(NSString*)ItemName:(NSMutableArray*)Data
{
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:Data] forKey:ItemName];
[[NSUserDefaults standardUserDefaults] synchronize] //add this code of a line.
}

How to retrive data from document directory when application start?

I have created application that record sound and display that sound file in tableview. In that application when sound is recorded than it's filepath will store in a array , which array i use to populate my tableview. But my problem is that when i close the application then my array will be empty , and i lost my recorded file.
So now how can i get my recorded file when i open my app second time. I am storing sound file in document directory.
Store array in NSUserDefaults. Retrive and Store the array in NSUserDefaults .. see the example of NSUserDefaults
In AppDelegate.h file just declare variable...
NSUserDefaults *userDefaults;
NSMutableArray *yourArray;
after...
In AppDelegate.m Fille in applicationDidFinishLonching: Method
userDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:#"yourArray"];
if (dataRepresentingtblArrayForSearch != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingtblArrayForSearch];
if (oldSavedArray != nil)
yourArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
yourArray = [[NSMutableArray alloc] init];
} else {
yourArray = [[NSMutableArray alloc] init];
}
[yourArray retain];
after that when you want to insert Data in this UserDefaults Use Bellow Code...
[appDelegate.yourArray addObject:yourDataString];///set your value or anything which you want to store here...
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:appDelegate.yourArray];
[appDelegate.userDefaults setObject:data forKey:#"yourArray"];
[appDelegate.userDefaults synchronize];
i hope this help you...

Saving ALAsset URL in NSUserDefaults

Hi I have my ALAsset URL save in NSMutableArray,
"ALAsset - Type:Photo, URLs:assets-library://asset/asset.JPG?id=119A0D2D-C267-4B69-A200-59890B2B0FE5&ex‌​t=JPG",
"ALAsset - Type:Photo, URLs:assets-library://asset/asset.JPG?id=92A7A24F-D54B-496E-B250-542BBE37BE8C&ex‌​t=JPG",
"ALAsset - Type:Photo, URLs:assets-library://asset/asset.JPG?id=77AC7205-68E6-4062-B80C-FC288DF96F24&ex‌​t=JPG
I wasnt able to save NSMutableArray in NSUserDefaults due to it having an error Note that dictionaries and arrays in property lists must also contain only property values.
Im thinking of using this :
- (void)encodeWithCoder:(NSCoder *)encoder {
//Encode properties, other class variables, etc
[encoder encodeObject:self.selectedPhotos forKey:#"selectedPhotos"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
//decode properties, other class vars
self.selectedPhotos = [decoder decodeObjectForKey:#"selectedPhotos"];
}
return self;
}
then save and retrieve it with this code:
- (void)saveCustomObject:(MyCustomObject *)obj {
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:obj];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:myEncodedObject forKey:#"myEncodedObjectKey"];
}
- (MyCustomObject *)loadCustomObjectWithKey:(NSString *)key {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [defaults objectForKey:key];
MyCustomObject *obj = (MyCustomObject *)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];
return obj;
}
But I somehow dont quite get it, still crashes in my code. Dont know how. And I wasnt able to save it in NSUserDefaults. Hope someone help. Really been having problem with this a while. Hope someone guide me on the right path of saving and retrieving it the right way from NSUserDefaults. Then back to a NSMutableArray.
The NSUserDefaults only takes a restricted set of classes as objects. See the documentation. You must take care only to store values of these types (NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary, and of course it applies recursively) in the dictionary.
To store the URLs in the NSUserDefaults, store them as strings, then read them back as URLs. If you need to have the dictionary in the current format, you may have to transform it before saving it.
- (void) saveMyUrls
{
NSMutableArray* urls = [NSMutableArray arrayWithCapacity:self.myUrls.count];
for(NSURL* url in self.myUrls) {
[urls addObject:[url absoluteString]];
}
[[NSUserDefaults standardUserDefaults] setObject:urls forKey:#"myUrls"];
}
- (void) loadUrls
{
NSArray* urls = [[NSUserDefaults standardUserDefaults] objectForKey:#"myUrls"];
self.myUrls = [NSMutableArray arrayWithCapacity:urls.count];
for(NSString* urlString in urls) {
[self.myUrls addObject:[NSURL URLWithString:urlString]];
}
[[NSUserDefaults standardUserDefaults] setObject:urls forKey:#"myUrls"];
}
If you need to save more information than just the URL, let's say a user-specified label, you could save the object as a NSDictionary instead, e.g.
- (void) saveMyUrlsWithLabels
{
NSMutableArray* objs = [NSMutableArray arrayWithCapacity:self.myObjects.count];
for(MyObject* obj in self.myObjects) {
[objs addObject:[NSDictionary dictionaryWithKeys:#"url", #"label"
forObjects:obj.url.absoluteString, obj.userSpecifiedLabel];
}
[[NSUserDefaults standardUserDefaults] setObject:objs forKey:#"myObjects"];
}
Maybe you should do it like this:
- (MyCustomObject *)loadCustomObjectWithKey:(NSString *)key {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults synchronize]; // note this
NSData *myEncodedObject = [defaults objectForKey:key];
MyCustomObject *obj = nil;
// it would be even better
// to wrap this into #try-#catch block
if(myEncodedObject)
{
obj = (MyCustomObject *)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];
}
return obj;
}
Also note that if you want to use NSKeyedArchiver and NSKeyedUNarchiver your MyCustomObject class has to conform to NSCoding protocol. Check NSCoding protocol reference and Archives and Serializations Programming Guide.
This is another way to do it and yes you can use NSUserDefaults. Basically you get asset URL, save it and then convert it back to an asset / image
//SET IT
ALAsset *asset3 = [self.assets objectAtIndex:[indexPath row]];
NSMutableString *testStr = [NSMutableString stringWithFormat:#"%#", asset3.defaultRepresentation.url];
//NSLog(#"testStr: %# ...", testStr);
[[NSUserDefaults standardUserDefaults] setObject:testStr forKey:#"userPhotoAsset"];
[[NSUserDefaults standardUserDefaults] synchronize];
//GET IT
NSString *assetUrlStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"userPhotoAsset"];
NSURL* aURL = [NSURL URLWithString:assetUrlStr];
NSLog(#"aURL: %# ...", aURL);
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:aURL resultBlock:^(ALAsset *asset)
{
UIImage *copyOfOriginalImage = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage] scale:1.0 orientation:UIImageOrientationUp];
imgVwPortrait.image = copyOfOriginalImage;
}
failureBlock:^(NSError *error)
{
// error handling
NSLog(#"failure-----");
}];

NSKeyedUnArchiver back to your original custom NSObject

I have an object i have made that is storing all information from twitter however i need to give it a load state so it needs to be saved to memory.
This is the code i have done so far below
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
rssParser = [[RssParser alloc] loadXMLbyURL:#"http://twitter.com/statuses/user_timeline/2smssupport.xml"];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:rssParser];
[prefs setObject:data forKey:#"Tweets"];
[prefs synchronize];
NSData *olddata = [prefs dataForKey:#"Tweets"];
I need to get the olddata back to its original form as an 'RssParser'
If anyone can help out it would be ace! its been ravaging my brain the last day or so!
Does RssParser implement NSCoding? If so, you just have to do
NSData *olddata = [prefs dataForKey:#"Tweets"];
RssParser *oldRssParser = (RssParser *)[NSKeyedUnarchiver unarchiveObjectWithData:olddata];
Otherwise you should read http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Archiving/Archiving.html%23//apple_ref/doc/uid/10000047-SW1

Facebook: obtain album id just created with Photos.createAlbum

I'm developing an iPhone app that creates a Photo Album to hold the pictures that the user is going to upload.
On - (void)request:(FBRequest*)request didLoad:(id)result { I'm trying to obtain the aid returned with this code:
else if ([#"Photos.createAlbum" isEqualToString: request.method]) {
NSLog(#"[Photos.createAlbum:dialogDidSucceed] succeed");
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *aid = [[NSString alloc] initWithString: [request.params objectForKey:#"aid"]];
[prefs setObject:aid forKey:_ALBUMID];
[prefs synchronize];
//[prefs release];
[aid release];
if (pendingUploadImage) {
[self btnUploadImage];
}
}
Here said that the aid is returned, but I don't know where.
How can I obtain album id?
If anywhere, it must be in result, which is a dictionary containing the response data from the web service. It certainly cannot be part of the request (where your code assumes it is).