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()
//加密使用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)
}
沒有留言:
張貼留言