Set NSURLSessionDownloadTask in NSMutableDictionary - ios

I set the NSURLSessionDownloadTask in NSMutableDictionary. Then I want to save this dictionary in NSUserDefaults.
I know that I can't save custom object in NSUserDefaults and, after searching, I've found this answer: How to store custom objects in NSUserDefaults, but I couldn't implement to my code.
Here is part of my code:
[self.downloadTasksDictionary setObject:dlTask forKey:[NSString stringWithFormat:#"%#",customId]];
[[NSUserDefaults standardUserDefaults] setObject:self.downloadTasksDictionary forKey:#"DownloadTaskDict"];
[[NSUserDefaults standardUserDefaults] synchronize];
Is there any way to save this NSMutableDictionary in NSUserDefaults?
Thanks.

You need to use NSKeyArchiver for this. Take a look at this SO post: Save custom objects into NSUserDefaults and Why does NSUserDefaults fail to save NSMutableDictionary?
But, why not saving request descriptor instead of downloadTask object?
In my project I have a NetworkManager which creates a NetworkTask from a NetworkRequest which is a struct. This struct can be created from a json. It works really well.

Related

Saved NSDictionary in NSUserDefaults isn't up to date

I have a simple messaging app, and I'm keeping a dictionary of BOOL:user in the NSUserDefaults which simply represents if something "new" has happened in that conversation. {YES:12343} for example, means there is a new message with user 123432, otherwise NO.
When users interact with each other, I update that dictionary and my view accordingly. And when I leave the app, save the dictionary to the NSUserDefaults. When I come back, I simply load it. Everything works smoothly, expect one thing.
When I tap on a conversation to open it, I set that boolean to NO (because I assume the user has read the message) and save that modified dictionary into the NSUserDefaults again.
Debug shows the dictionary is up to date when saved, but when I tap the "back" button, the view reloads the dictionary from the NSUserDefaults and that dictionary is NOT up to date. So my view is showing the conversation as unread, obviously.
Now the tricky parts comes into play. If I do it again, (sometimes once, sometimes twice), the dictionary will eventually show the conversation as read (because the dictionary will finally be up to date).
This tells me some things :
The dictionary is readable and everything is set "as it should/when it should"
What I get from the NSUserDefaults isn't updated quick enough/at the right time.
What I fail to understand is : when should I save that dictionary and how? I'm loading it in viewWillAppear, and saving it in didSelect. Isn't that the right thing to do ?
Some code :
My didSelect :
pushDict is an NSMutableDictionary object and is never nil at that point
if (pushDict != nil){
[pushDict setObject:[NSNumber numberWithBool:NO] forKey:_friendship.objectId];
[[NSUserDefaults standardUserDefaults]setObject:pushDict forKey:#"pushDict"];
}
And the dictionary loading :
if([[NSUserDefaults standardUserDefaults]dictionaryForKey:#"pushDict"]){
pushDict = [[NSMutableDictionary alloc]initWithDictionary:[[NSUserDefaults standardUserDefaults]dictionaryForKey:#"pushDict"]];
}else{
pushDictFeel = [NSMutableDictionary alloc]init];
}
First of all NSUserDefaults shouldn't be the place where you save information like this. Try to setup a good data model for this. However your error could occure because you are missing this line:
[[NSUserDefaults standardUserDefaults] synchronize];
From your code I can see that you are trying to save a NSMutableDictionary. This will not work since the returned object from the NSUserDefaults is immutable. Have a look at this:
NSMutableDictionary in NSUserDefaults
You need to call synchronize for [NSUserDefaults standardUserDefaults]
if (pushDict != nil){
[pushDict setObject:[NSNumber numberWithBool:NO] forKey:_friendship.objectId];
[[NSUserDefaults standardUserDefaults]setObject:pushDict forKey:#"pushDict"];
[[NSUserDefaults standardUserDefaults] synchronize];
}

how to achieve caching the data of web services locally retrieve back in iPhone Application?

I'm new for iOS, i'm using AF-Networking framework for fetching the web services and successfully getting the data and loading it to the UI elements now what's my issue is Application performance is slow and it's loading form the web service every time i want to cache the images and data locally and increase the performance of the application can anyone out there can help me with the proper solution.
Thanks in Advance
I think what you are talking about has nothing to do with NSURLCache but to save the previous network request data locally. Then next time before you send a network request you can read from local file first
There are many different ways of saving data locally like Core Data NSKeyedArchiver plist FMDB. Here is my way using NSKeyedArchiver.
(put the interface here you can read the implementation at this link https://github.com/dopcn/HotDaily/blob/master/HotDaily/HDCacheStore.m)
#interface HDCacheStore : NSObject
+ (HDCacheStore *)sharedStore;
#property (copy, nonatomic) NSArray *mainListCache;
#property (copy, nonatomic) NSArray *funinfoListCache;
- (BOOL)save;
#end
in XXXAppDelegate.m
- (void)applicationWillResignActive:(UIApplication *)application //Or some other place
{
if ([[HDCacheStore sharedStore] save]) {
NSLog(#"save success");
} else {
NSLog(#"save fail");
}
}
I think you have to use NSUserDefaults, follow the following
1: create NSArray of the data u need
2: Save into NSUserDefaults with a key
3: Now you are able to use that NSArray in every class of the application
4: if you want update data simply again save into NSUserDefaults with old key
So you don't need to download data every time, just download once and save into NSUserDefaults and use.
if there is problem in saving data in NSUserDefaults then look at code bellow
To store the information:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:arrayOfImage forKey:#"tableViewDataImage"];
[userDefaults setObject:arrayOfText forKey:#"tableViewDataText"];
To retrieve the information:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSArray *arrayOfImages = [userDefaults objectForKey:#"tableViewDataImage"];
NSArray *arrayOfText = [userDefaults objectForKey:#"tableViewDataText"];
// Use 'yourArray' to repopulate your UI

how do i manage the number of views and likes on app ios

i have tried to look for a way to manage the number of views and likes on videos in iOS but i don't know the best way to do it or the safest way since i'm saving it to memory do i use NSUserDefault
Yes. You can use NSUserDefault. It is to store the data and you can retreive it from any place of the projects. It can be done by following way:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:yourdata forKey:#"keyName"];
[userDefaults synchronize];
Write the below code where you want to get the saved data in userdefaults.
NSUserDefaults *userDefauls = [NSUserDefau;ts standardUserDefaults];
value = [userDefaults objectForKey:#"keyName"];

Store a user profile in iOS appĀ so that it's always accessible

I want to create a user that the app fetches from disk every time the app is opened, and written every time it is closed. I want the data from the user, such as NSString name, along with some other variables, to be accessible from any other point in the app.
There will only be one user so it is kind of a "global" variable. Also, if the user class includes pointers to data structures like NSMutableDictionary, or another instance of NSObject, are there any precautions I need to take?
I want to learn the best way to implement this, any suggestions?
NSUserDefaults is your friend. It meets your requirements to be accessible from any other point in the app.
1) Create a class to represent your user
2) Have that class implement the NSCoding protocol
3) Use NSFileManager to create or open a file as necessary
4) Use that file to restore / store the user class. (Its easy using the NSCoding protocol)
5) Make the user class owned by your model which exposes the data in the user class, or make the user class a singleton (The first is much better).
You should be able to find examples / tutorials if you search how to store stuff using NSCoding
You can create an UserObject extended by NSObject. Use a Singleton Pattern so you always have the same object inside every class.
Then you could just save every variable inside NSUserDefaults by using a specific key.
If you want to save the whole object inside NSUserDefaults you need to include the NSCoding in the interface
#interfaces User : NSObject <NSCoding>
and use the methods initWithCode: and encodeWithCoder:
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if( self ){
strName = [aDecoder decodeObjectForKey:#"name"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:strName forKey:#"name"];
}
for un / archiving do it this way:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:userObject];
UserObject *user = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if you want some more information you can read all about it here.
Use keychain in case there is private user data to store.
In most cases Martin's answer is the best way.
NSUserDefaults is a great option. You can access it from every point on your app, save and extract data anytime and store most of the things you'll probably need.
To save:
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
[userDef setObject:userDictionary forKey:#"userData"];
[userDef synchronize];
To Extract:
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
NSDictionary *userDictionary = [userDef objectForKey:#"userData"];
You can save your data on your AppDelegate's
- (void)applicationWillTerminate:(UIApplication *)application;
And Extract on:
- (void)applicationWillEnterForeground:(UIApplication *)application;

Save data on iphone app [duplicate]

This question already has answers here:
Best way to save data on the iPhone
(7 answers)
Closed 9 years ago.
I want to save some initial settings values given by the user when the app is open for the first time, If the values are saved it shouldn't be appear next time. How to save these values inside the app. Some suggested to use .plist , while searched regarding this. Is that the right approach? or there any simpler option available?
I would suggest saving the information in an array and then saving the array on the NSUserDefaults singleton that is integrated on the device. That way you can always access the information from anywhere.
Have in mind that this approach is only viable if the info is small enough.
To save on the NSUserDefaults class:
[[NSUserDefaults standardUserDefaults] setObject:yourMutableArray forKey:#"Key"];
To get the value:
NSMutableArray *array = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults]
objectForKey:#"Key"]];
The easiest option is to save these value in form of key-value pair into NSUserDefaults.
NSUserDefaults *stdDefaults = [NSUserDefaults standardUserDefaults];
if([stdDefaults objectForKey:#"APP_OPENED"] == FALSE)
{
[stdDefaults setValue:#"YOUR_VALUE" forKey:#"YOUR_KEY"];
//Store more values if you wish
[stdDefaults setBool:YES forKey:#"APP_OPENED"];
[stdDefaults synchronize];
}
If you want to save non encrypted data, you can use NSUserDefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:txtfield1.text forKey:#"info1"];
[defaults setObject:txtfield2.text forKey:#"info2"];
[defaults synchronize];
If it includes passwords, better to use KeyChain. Otherwise, NSUserDefaults would be a good choice...
I would suggest using NSUserDefaults. Something like this:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL hasOpenedAppBefore = [defaults boolForKey:#"hasOpenedAppBefore"];
[defaults setBool:YES forKey:#"hasOpenedAppBefore"];
You can use NSUserDefaults which can store data
Read apple's doc
Make use of NSUserDefaults to store the data. The stored data can retrieved and modified whenever necessary.
Read NSUserDefaults Class Reference
Read Tutorial
NSUserDefaults is the best option for store data inside application and you can easily use it throughout the application.

Resources