[iOS] Swift: How to store user preferences?

Apple 官方教學:
https://developer.apple.com/documentation/foundation/userdefaults


You can use NSUserDefaults to save information and retrieve it next time when the app launches.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html

For Save example:

UserDefaults.standard.setValue(UserId, forKey: "UserId")

 

For Load example:

let tmpUserId = UserDefaults.standard.string(forKey: "UserId")
if (tmpUserId != nil) {
 UserId = tmpUserId!
}

Use NSUserDefaults

Let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("User", forKey: "userName")

Check if User name exists when application is started in your AppDelegate.swift

didFinishLaunchingWithOptions

If username exists, skip login page

To check if NSUserDefaults is nil

if (defaults.objectForKey(userName) != nil) { 
// Skip Login 
}
else {// Show login 
} 

 

Objective-C 版本:

Save:

NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];

to get it back later:

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"preferenceName"];

 

 


這個範例有點特別,如果是 self sign 的話,可以會跑進這一個 method:

– (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler

 

如果是合法的 sign 的話,只會跑進下面的不會跑上面的;

如果是 self sign 上面/下面都會執行,結論,是使用下面這組:

-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *