2017年6月6日 星期二

Swift3 UIWebView 和 WKWebView的基本運用(觸發超連結)

      今天要來講如何運用UIWebViewWKWebView的套用(讀取網頁)跟點擊後觸發要做的事情。一般新手或是因為方便也可能是習慣多數人都是使用UIWebView,而小弟我也是習慣用UIWebView,可是用過的人應該都會發現UIWebView在效能上來講並沒有比較好。又剛好某些原因需要做到觸發,於是發現了WKWebView,他效能上比UIWebView好,也是很多高手比較推薦使用的。
最下面會放上我開啟網頁的圖片,注意請使用實機測試會比較好喔!

這邊而外提一下,我所使用的網頁是利用firebase所製作出來的,所以並會停供測試的url。可能需要您自己去建立唷^^怎麼建立就不多說了,畢竟這裡主要講的是swift3

直接先附上storyboard的截圖,非常的簡單。我是為了一次呈現兩種所以做了兩個頁面給各位參考。

上圖中兩個都是ViewController,但一個有加入UIWebView

先來說UIWebView的運用吧!下面直接就附上Code並有附帶註解所以不而外做說明了

import UIKit

class WebViewController: UIViewController,UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //加入delegate因為要做觸發判斷
        webView.delegate = self
        //載入網頁
        let url = URL(string: "你的網頁位子");
        webView.loadRequest(URLRequest(url: url!))
        
    }

    //當用戶點擊觸發事件(我本身自己做的是觸發連結)
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //判斷觸發的連結
        if (navigationType == .linkClicked){
            let str:String = (request.url?.scheme)!
            switch str {//利用switch判斷點擊後傳出來的url而決定動作
            case "mailto"://信箱
                //如果沒有要特地加載主旨或內容可以忽略下面內容直接跳掉開啟url即可
                let subject = "UIWebViewDome"//主旨
                let body = "這是UIWebView運用於點擊事件是發送mail"//信件內文
                let coded = "\(request)?subject=\(subject)&body=\(body)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
                //開啟信箱
                //(因為openURL前方有帶入字串"mailto:"所以系統會自動判斷開啟信箱而非safari)
                if let emailURL:URL = URL(string: coded!){
                    if UIApplication.shared.canOpenURL(emailURL){
                        UIApplication.shared.openURL(emailURL)
                    }
                }
                case "tel"://電話
                    //一般來講網頁端如果有做好就不用做下面的動作,做了其實是多餘的。除非網頁端只有提供一般電話號碼的字串並沒有帶tel:那樣的話就需要自己在做url並作下面的動作
                    
//                    let url = URL(string: (request.url?.scheme!)!)
                    let tel = "0987654321"
                    let url = URL(string: "tel:\(tel)")
                    if UIApplication.shared.canOpenURL(url!){
                        UIApplication.shared.openURL(url!)
                }
            default:
                break
            }
            
        }
        return true

    }

再來就是WKWebView這邊會多做一點說明。因為做法稍微不同
就一般新手來說使用WKWebView會感到困擾就是要都用寫的而選擇不用。
但是其實官方的教學就顯而易懂,而且不用特地在做constraints。
而我也直接用官方範例的方法寫,再參考Code裡面loadView()的內容吧!這個func會執行得比viewdidload還早唷!
注意!!!記得要import WebKit 並且宣告var webView:WKWebView! 並且加入代理人WKUIDelegate,WKNavigationDelegate

接下來就直接附上code了,一樣內有註解

import UIKit
import WebKit

@available(iOS 10.0, *)
class ViewController: UIViewController,WKUIDelegate,WKNavigationDelegate {

    var webView:WKWebView!
    
    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //載入網頁
        let url = URL(string: "你的網頁位子");
        webView.load(URLRequest(url: url!))
        
    }
   
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        print("webview:\(webView) decidePolicyFornavigationAction:\(navigationAction) decisionHandler:\(decisionHandler)")
        //判斷點擊觸發事件
        switch navigationAction.navigationType {
        case .linkActivated://點擊事件
            if navigationAction.targetFrame == nil{
                self.webView.load(navigationAction.request)
            }
            let url = navigationAction.request.url
            let str:String = (url?.scheme!)!
            switch str {//判斷點擊到的事件是什麼要幹嘛
            case "mailto"://信箱
                print("mail")
                let subject = "UIWebViewDome"//主旨
                let body = "這是UIWebView運用於點擊事件是發送mail"//信件內文
                let coded = "\(navigationAction.request)?subject=\(subject)&body=\(body)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
                
                //開啟信箱
                //(因為openURL前方有帶入字串"mailto:"所以系統會自動判斷開啟信箱而非safari)
                if let emailURL = URL(string: coded!){
                    if UIApplication.shared.canOpenURL(emailURL){
                        UIApplication.shared.openURL(emailURL)
                    }
                }

                decisionHandler(.cancel)
                return
            case "tel"://電話
                //一般來講網頁端如果有做好就不用做下面的動作,做了其實是多餘的。除非網頁端只有提供一般電話號碼的字串並沒有帶tel:那樣的話就需要自己在做url並作下面的動作
                //但是!wkWebView是不管怎樣都必須要告知你要做的動作所以下面動作必須要做!
                print("tel")
              let number:String = (url?.absoluteString)!
                //因為apple一般會要求開發者在用戶做某些特定動作時必須要有提醒(例如取用相機之類的),所以在這做了一個AlertController來提醒用戶撥出通話。
                let alertController = UIAlertController(title: nil, message: "\(number.replacingOccurrences(of: "tel:", with: ""))", preferredStyle: .alert)
                alertController.addAction(UIAlertAction(title: "取消", style: .default, handler: nil));
                alertController.addAction(UIAlertAction(title: "通話", style: .default, handler: { (action:UIAlertAction) in
                    if UIApplication.shared.canOpenURL(navigationAction.request.url!){
                        UIApplication.shared.openURL(navigationAction.request.url!)
                    }
                }));
                
                
               self.present(alertController, animated: true, completion: nil)
                
            default:
                break
            }
             default:
            break
        }

        decisionHandler(.allow)

    }



2017年5月7日 星期日

Swift3 AlertController 的一些基本運用

今天要來寫AlertController的一些運用,使用都是原生的Code,在iOS9以後apple要求使用AlertController,在這之前大家都是使用已經停的AlertView。如果你遇到要使用的情況建議使用AlertController唷!畢竟官方已經停用AlertView
有一個小小的提醒就是當您在練習時記得不要將AlertController寫在viewdidLoad因為可能會沒顯示出來,建議使用一個button或是在比viewdidLoad晚執行的時候處理

一般的AlertController建立

 let alertController = UIAlertController(title: "建立Alert", message: "建立成功了唷!", preferredStyle: .alert);
        //建立AlertAction,如果再按下Action後要做動作就將print的位子寫入你要的動作,像取消通常沒做動作可將handler帶入nil即可
        let alertActionOK = UIAlertAction(title: "確定", style: .default, handler: {
            action in
            print("寫入你要的動作");
        });
        let alertActionCancel = UIAlertAction(title: "取消", style: .destructive, handler: nil);//style通常都是使用default,如使用.destructiveaction會直些顯示紅色
        
        alertController.addAction(alertActionOK);//AlertController加入確定鈕
        alertController.addAction(alertActionCancel);//AlertController加入取消鈕
        //顯示出AlertController的方法有下面兩種。
        self.present(alertController, animated: true, completion: nil);

//        self.show(alertController, sender: nil);


改變AlertController的背景色

 let alertController = UIAlertController(title: "背景色?", message: "改變背景色", preferredStyle: .alert);
        //加入背景色
        let firstView = alertController.view.subviews.first;
        let backView = firstView?.subviews.first;
        for subview in (backView?.subviews)!{
            subview.backgroundColor = UIColor.yellow;
            subview.layer.cornerRadius = 10.0;
            subview.alpha = 1;
        }
        
        let alertActionOK = UIAlertAction(title: "確定", style: .default, handler: nil);
        alertController.addAction(alertActionOK);
        self.present(alertController, animated: true, completion: nil);



改變AlertAction的文字顏色

let alertController = UIAlertController(title: "Action顏色", message: "改變Action顏色", preferredStyle: .alert);
      //這行是兩個Action顏色都改一樣
//        alertController.view.tintColor = UIColor.brown
        
        let alertActionOK = UIAlertAction(title: "確定", style: .default, handler: nil);
        //改變ActionOK的顏色為橘色
        alertActionOK.setValue(UIColor.orange, forKey: "titleTextColor");
        
        let alertActionCancel = UIAlertAction(title: "取消", style: .default, handler: nil);
//        改變ActionCancel的顏色為綠色
        alertActionCancel.setValue(UIColor.green, forKey: "titleTextColor");
        
        alertController.addAction(alertActionOK);
        alertController.addAction(alertActionCancel);
        self.present(alertController, animated: true, completion: nil);



改變AlertController的Title文字顏色

 let alertController = UIAlertController(title: "Title顏色改變", message: "預設顏色為黑色唷!改為紅色了", preferredStyle: .alert);
        let myTitleString = NSMutableAttributedString(string: "Title顏色改變",
                                                      attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!]);
        myTitleString.addAttribute(NSForegroundColorAttributeName,
                                   value: UIColor.red,
                                   range: NSRange(location: 0,
                                                  length: "Title顏色改變".characters.count));
        
        alertController.setValue(myTitleString, forKey: "attributedTitle");
        
        let alertActionOK = UIAlertAction(title: "確定", style: .default, handler: nil);
        alertController.addAction(alertActionOK);
        self.present(alertController, animated: true, completion: nil);




改變AlertController的Message文字顏色

 let message = "改變訊息的顏色變為橘色了喔!"
         let alertController = UIAlertController(title: "Message顏色改變", message: message, preferredStyle: .alert);
        let messageMutableString = NSMutableAttributedString(string: message, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 15.0)!]);
        messageMutableString.addAttribute(NSForegroundColorAttributeName,
                                          value: UIColor.orange,
                                          range: NSRange(location: 0, length: message.characters.count));
        
        alertController.setValue(messageMutableString, forKey: "attributedMessage");
        
        let alertActionOK = UIAlertAction(title: "確定", style: .default, handler: nil);
        alertController.addAction(alertActionOK);
        self.present(alertController, animated: true, completion: nil);



AlertController中加入TextField

 let alertController = UIAlertController(title: "加入textField?", message: "下方有TextField", preferredStyle: .alert);
        alertController.addTextField(configurationHandler: {(textField : UITextField!) -> Void in
            textField.placeholder = "請輸入文字"
            //怎麼運用看個人了喔!如果想要鎖定字數之類的請慘考此篇http://h81061678.blogspot.tw/2016/12/swift3-alertaction.html
        });
        let alertActionOK = UIAlertAction(title: "確定", style: .default, handler: nil);
        alertController.addAction(alertActionOK);

        self.present(alertController, animated: true, completion: nil);



以上的用法希望能夠對大家有幫助唷!

2017年3月7日 星期二

swift3 TextField監控決定UIButton的動作或顏色

最近剛好遇到設計如果欄位是空的話就將Btn顯示一個顏色,如果用戶輸入了文字後有內容了在改變顏色,這邊直接附上code做兩種不樣的功能,上面屬於Btn變色,下面屬於鎖住Btn
不多說直接附上code跟模擬畫面

import UIKit

class ViewController: UIViewController,UITextFieldDelegate,UITextViewDelegate {
    
    var singleFingerTap:UITapGestureRecognizer!
    var text1Bool:Bool!
    
    
    @IBOutlet weak var textfield1: UITextField!
    
    @IBOutlet weak var textfield2: UITextField!
    
    @IBOutlet weak var btn1: UIButton!
    @IBOutlet weak var btn2: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //監聽鍵盤動作
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil);
        singleFingerTap = UITapGestureRecognizer.init(target: self, action: #selector(handleSingleTap));
        
        self.textfield1.delegate = self
        self.textfield2.delegate = self
        textfield1.clearButtonMode = .always
        textfield2.clearButtonMode = .always
        btn1.backgroundColor = UIColor.red
        btn2.backgroundColor = UIColor.gray
        btn1.tintColor = UIColor.white
        btn2.tintColor = UIColor.white
        text1Bool = false
        
        textfield1.addTarget(self, action: #selector(text1(textfield:)), for: .allEditingEvents)
        textfield2.addTarget(self, action: #selector(text2(textfield:)), for: .allEditingEvents)
    }
    func btn1c(){
        if (text1Bool == true){
            btn1.backgroundColor = UIColor.brown
        }else{
            btn1.backgroundColor = UIColor.red
        }
    }
   
    func text1(textfield:UITextField){
//        if ((textfield.text?.characters.count)! < 2){
        if (textfield1.text != ""){
            text1Bool = true
        }else{
            text1Bool = false
        }
        self.btn1c()
    }
    func text2(textfield:UITextField){
       self.btn2.isEnabled = (textfield.text?.characters.count)! > 2
        
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: 鍵盤監聽動作(當用戶點view收起)
    func keyboardWasShown(){
        self.view.addGestureRecognizer(singleFingerTap);
    }
    func keyboardWasHidden(){
        self.view.removeGestureRecognizer(singleFingerTap);
    }
    func handleSingleTap(){
        //Do stuff here...
        textfield1.resignFirstResponder()
        textfield2.resignFirstResponder()
    }


    @IBAction func Btn1(_ sender: Any) {
        print(textfield1.text!)
    }
    @IBAction func Btn2(_ sender: Any) {
        print(textfield2.text!)
    }

}





希望能夠幫助到有需要的朋友們唷^^
雖然手法有點粗操,有更好的方法歡迎提供!



2017年2月8日 星期三

Swift3 使用MD5

MD5的應用,花了一點點小時間參考別人的文章而做出來的
一開始做的時候看到大家都說要引入
#import <CommonCrypto/CommonDigest.h>
我一開始想說直接在swift內呼叫,發現怎麼樣都叫不到
後來想到MD5應該屬於C,所以這邊使用swift的朋友們別忘了建立橋接
橋接建立方法最偷懶最方便的方法建立cocoa touch class 將語言改成OC
然後按確定後會顯示下圖
 記得要按下建立橋接如下圖
 建立好後會如下圖
這時候在橋接內引入 #import <CommonCrypto/CommonDigest.h>
小提醒:如果OC的class沒用到可以刪掉沒關係,
因為我們只是方便建立橋接省去麻煩
然後建立一個新的swift file
我個人這邊檔名直接設定為MD5而程式碼如下
import Foundation

extension String {
    func md5() -> String {
        let str = self.cString(using: .utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: .utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize()
        return String(format: hash as String)
    }
}
最後直接在viewcontroller.swift的viewdidload內測試摟
你可以建立一個string或者是直接print
let string = "123456"
        print(string.md5())
        print("MD5測試".md5())

測試出來結果如下
e10adc3949ba59abbe56e057f20f883e
ee4580a7e015144cbfaa8ba05f742cba

可以到線上的測試網站測試看看喔!!

2017年1月25日 星期三

swift3 使用原生播放器AVPlayerViewController

這邊不多說了,直接附上Code給大家參考
而程式碼裡面會看到有三個button
第一個PlayBtn所使用的方法是直接開啟AVPlayerViewController做播放
並且要自行在點擊播放(如需自動播放加入.play()即可)
第二個InViewBtn所使用的方法是在storyboard裡面建立一個View(自訂大小)然後將AVPlayer放入View裡面並且直接自動播放player.play()
第三個就是將在view內播放時可按暫停
其他深入的小功能就靠大家自行摸索摟~

//
//  ViewController.swift
//  AVPlayer
//
//  Created by John on 2017/1/23.
//  Copyright © 2017 John. All rights reserved.
//

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {
    
    @IBOutlet weak var UrlText: UITextField!
    @IBOutlet weak var PlayerView: UIView!
    var player:AVPlayer!
    var Bool:Bool! = false
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func PlayBtn(_ sender: UIButton) {
        
        let url = URL(string: UrlText.text!)

        player = AVPlayer(url: url!)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player;
        self.present(playerViewController, animated: true, completion: nil)
        //  player.play()
        
    }
    
    @IBAction func InViewBtn(_ sender: UIButton) {
        let url = URL(string: UrlText.text!)
        player = AVPlayer(url: url!);
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.PlayerView.bounds
        self.PlayerView.layer.addSublayer(playerLayer)
        player.play()
        Bool = true
    }
    @IBAction func Player(_ sender: UIButton) {
        
        if Bool == true{
            player.pause()
            Bool = false
        }else{
            player.play()
            Bool = true
        }
        
    }
}


大致架構就這樣。。影片流自行收尋吧^^