2016年9月21日 星期三

判斷APP是否第一次開起(Swfit)

當我們要判斷用戶是否第一次開起APP時必須在APPDelegate的didFinishLauchingWithOptions下存取兩組BOOL進去userDefaults
再利用存進去的userDefaults做判斷
第一次啟動為true
之後將第二個BOOL變為false


  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
判斷當"abcd"如果是false或是空時做什麼動作,如果不是空就跳到else也就是非第一次開起

        if(!UserDefaults.standard.bool(forKey: "abcd")){
            UserDefaults.standard.set(true, forKey: "abcd")
            UserDefaults.standard.set(true, forKey: "first")
            print("first")
        }else{
            UserDefaults.standard.set(false, forKey: "first")
            print("unfirst")
        }
        
        
        
        return true

    }

簡單的做個lable來測試是否有判斷成功(也可使用alert)
 override func viewDidLoad() {
        super.viewDidLoad()
    
        if (UserDefaults.standard.bool(forKey: "first")){

           let lable = UILabel(frame: CGRect(x: 50, y: 200, width: 200, height: 36))
            lable.text = "第一次開起"
            lable.backgroundColor = UIColor.red
            lable.textColor = UIColor.yellow
            self.view.addSubview(lable)
        }else{

            let lable = UILabel(frame: CGRect(x: 50, y: 200, width: 200, height: 36))
            lable.text = "非第一次開起"
            lable.backgroundColor = UIColor.blue
            lable.textColor = UIColor.white
            self.view.addSubview(lable)
        }
    }

下圖為測試結果


2016年9月12日 星期一

監聽動作 (Swift)

下列程式碼為簡單的監聽應用,監聽可運用在很多地方。

監聽函數NSNotificationCenter.defaultCenter().addObserver(<#T##observer: AnyObject##AnyObject#>,<-self
 selector: <#T##Selector#>, <-自定義的func名稱,記得前面要帶上#selector(controller名稱.func名稱)
name: <#T##String?#>, <-自定義一個名稱,當呼叫監聽時需要用到
object: <#T##AnyObject?#>)<-如沒有object動做時則為nil,目前我用到幾乎都是使用nil

呼叫監聽動作函數NSNotificationCenter.defaultCenter().postNotificationName(
<#T##aName: String##String#>,<-在監聽時自定義的名稱
object: <#T##AnyObject?#>)<-同監聽時的object

監聽動作函數有很多種可以選擇,使用時可多研究哪一種是你當下需求最好的。

Swift 3
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
//        當值行以下時進行監聽動作
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.leableText), name: NSNotification.Name(rawValue: "test"), object: nil)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func button(sender: UIButton) {
//        間聽到時值行該動作
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "test"), object: nil);
    
    }

    func leableText(){
        label.text = "監聽";
        label.textColor = UIColor.blue
        label.backgroundColor = UIColor.red
    }

}

Swift2.3
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
//        當值行以下時進行監聽動作
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.leableText), name: "test", object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func button(sender: UIButton) {
//        間聽到時值行該動作
        NSNotificationCenter.defaultCenter().postNotificationName("test", object: nil);
    }

    func leableText(){
        label.text = "監聽";
        label.textColor = UIColor.blueColor()
        label.backgroundColor = UIColor.redColor()
    }
}


執行動作前如下圖
因viewDidLoad設定了監聽,
所以APP一執行時就進行了監聽func leableText()裡面要執行的程序
當點擊button則執行監聽動作如下圖





UserDefaults 資料存取(Swift)

存取欄位資料
Swift 3

2016/11/16補充
今天補充swift3在其他class時使用UserDefaults取出原本以存入的資料
首先可先建立一個新的class,在這我直接建立兩個新的label及一個button
button內所做的就是將原本前一個class已經輸入的資料呼叫出來並輸入新建立的label
當我們存入資料時是使用UserDefaults.standard.setValue(Any?, forKey: String)
呼叫資料時使用UserDefaults.standard.string(forKey: String)

@IBOutlet weak var passwordLabel: UILabel!

@IBOutlet weak var IdLabel: UILabel!

 @IBAction func loadingBtn(_ sender: UIButton) {
        IdLabel.text = UserDefaults.standard.string(forKey: "id")
        passwordLabel.text = UserDefaults.standard.string(forKey: "pas")
    }
-------------------------------------------------虛線以上為補充----------------------------------------------------

import UIKit


class ViewController: UIViewController,UITextFieldDelegate {
    
    
    @IBOutlet weak var ID: UITextField!
    @IBOutlet weak var PassWord: UITextField!
    
    var UserDef:UserDefaults!
    var Id:String!
    var pas:String!
    var info:String!
    var info2:String!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        ID.delegate = self
        PassWord.delegate = self
        //        ID.enablesReturnKeyAutomatically = true
        //        PassWord.enablesReturnKeyAutomatically = true
        UserDef = UserDefaults.standard
        
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func OKButton(sender: UIButton) {
        
        Id = ID.text;
        pas = PassWord.text;
        UserDef.setValue(Id, forKey: "id")
        UserDef.setValue(pas, forKey: "pas")
        
        
        info = UserDef.string(forKey: "id");
        info2 = UserDef.string(forKey: "pas");
        
        //        print(info)
        //        print(info2)
        
        
    }
    
    @IBAction func PrintButton(sender: UIButton) {
        
        let leable:UILabel = UILabel.init(frame: CGRect(x: 50, y: 200, width: 100, height: 36));
        leable.backgroundColor = UIColor.red
        
        let leable2:UILabel = UILabel.init(frame: CGRect(x: 50, y: 237, width: 100, height: 36));
        leable2.backgroundColor = UIColor.red
        
        
        
        if let userID = UserDef.string(forKey: "id"){
            
            leable.text = userID
            self.view.addSubview(leable);
            
        }else{
            leable.backgroundColor = UIColor.blue
            
        }
        if let aaa = UserDef.string(forKey: "pas"){
            leable2.text = aaa
            self.view.addSubview(leable2)
        }else{
            leable2.backgroundColor = UIColor.blue
        }
        
    }
}




Swift 2.3

import UIKit


class ViewController: UIViewController,UITextFieldDelegate {
    
    
    @IBOutlet weak var ID: UITextField!
    @IBOutlet weak var PassWord: UITextField!
    
    var UserDef:NSUserDefaults!
    var Id:String!
    var pas:String!
    var info:String!
    var info2:String!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        ID.delegate = self
        PassWord.delegate = self
//        ID.enablesReturnKeyAutomatically = true
//        PassWord.enablesReturnKeyAutomatically = true
        UserDef = NSUserDefaults.standardUserDefaults()
        
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func OKButton(sender: UIButton) {
        
        Id = ID.text;
        pas = PassWord.text;
        UserDef.setValue(Id, forKey: "id")
        UserDef.setValue(pas, forKey: "pas")
        
        
         info = UserDef.stringForKey("id");
         info2 = UserDef.stringForKey("pas");
        
        print(info)
       print(info2)
        
        
    }
    
    @IBAction func PrintButton(sender: UIButton) {
        
        let leable:UILabel = UILabel.init(frame: CGRect(x: 50, y: 200, width: 100, height: 36));
        leable.backgroundColor = UIColor.redColor()
        
        let leable2:UILabel = UILabel.init(frame: CGRect(x: 50, y: 237, width: 100, height: 36));
        leable2.backgroundColor = UIColor.redColor()
        

        
        if let userID = UserDef.stringForKey("id"){
           
            leable.text = userID
            
        self.view.addSubview(leable);
        
        }else{
        leable.backgroundColor = UIColor.blueColor()
            
        }
        if let aaa = UserDef.stringForKey("pas"){
            leable2.text = aaa
            self.view.addSubview(leable2)
        }else{
            leable2.backgroundColor = UIColor.blueColor()
        }
        
    }

}

第一次輸入後畫面如下
 將APP玩全關必後開起在值接按書出後顯是如下



如按下輸出後沒顯示出來label被景為藍色時表示存取沒有成功或資料是空


BASE64加密(Swift)

使用原生簡易加密BASE64

Swift 3

import UIKit

class ViewController: UIViewController {
    
    var base64String:String!
    var Lable1:UILabel!
    var Lable2:UILabel!
    
    @IBOutlet weak var string: UITextField!
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        string.backgroundColor = UIColor.brown
        string.alpha = 0.7;
        
        Lable1 = UILabel.init(frame: CGRect(x: 10, y: 150, width: 320, height: 36));
        Lable1.backgroundColor = UIColor.gray
        Lable1.alpha = 0.5
        
        Lable2 = UILabel.init(frame: CGRect(x: 10, y: 190, width: 320, height: 36));
        Lable2.backgroundColor = UIColor.red
        Lable2.alpha = 0.5;
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func encryptionBtn(_ sender: UIButton) {
        let StringText = string.text;
        let base64Data = StringText!.data(using: String.Encoding.utf8)
        
        base64String = base64Data?.base64EncodedString(options: .lineLength64Characters)
        
        print(base64String)
        
        Lable1.text = "這是加密結果:\(base64String)";
       
        self.view.addSubview(Lable1);
    }
    
    @IBAction func UnencryptionBtn(_ sender: UIButton) {
        if(base64String != nil){
            let decodedData = Data(base64Encoded: base64String!, options: .ignoreUnknownCharacters)
            
            let decodedString = NSString(data: decodedData!, encoding: String.Encoding.utf8.rawValue) as! String
            
            print(decodedString)
            
            Lable2.text = "這是解密結果:\(decodedString)";
            self.view.addSubview(Lable2);
        }
    }
    @IBAction func cleanBtn(_ sender: UIButton) {
        string.text = nil
        
        Lable1.text = ""
        Lable1.removeFromSuperview()
        
        Lable2.text = ""
        Lable2.removeFromSuperview()
    }

}

Swfit 2.3

override func viewDidLoad() {

        super.viewDidLoad()

let string = "test"

  //加密使用base64
           
let base64Data = string.dataUsingEncoding(NSUTF8StringEncoding)
            
let base64String = base64Data?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
          
  print(base64String)  //輸出後會變成(dGVzdA==)
       
     //解密base64
      
      let decodedData = NSData(base64EncodedString: base64String!, options: .IgnoreUnknownCharacters)
           
let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)

          
  print(decodedString)//輸出後會恢復(test)
}