原由javascript
最近須要作個IOS的殼子,用到長按保存圖片的功能,發現百度出來的全是OC語法的例子,不少都不是全面,只能本身寫一份Swift版本的,圖片下面附上Github地址java
效果圖git
Github地址:https://github.com/goyuanfang/SwifLongTouchSavePicgithub
原理web
UIWebView中 ide
func webViewDidFinishLoad(webView: UIWebView) lua
加載完URL後注入監聽手機觸摸屏幕的js腳本:url
document.ontouchstart=function(event){
x=event.targetTouches[0].clientX;
y=event.targetTouches[0].clientY;
document.location="myweb:touch:start:"+x+":"+y;
};
document.ontouchmove=function(event){
x=event.targetTouches[0].clientX;
y=event.targetTouches[0].clientY;
document.location="myweb:touch:move:"+x+":"+y;};
document.ontouchcancel=function(event){
document.location="myweb:touch:cancel";
};
document.ontouchend=function(event){
document.location="myweb:touch:end";
};
每次監聽到手指移動都會將修改document的頁面定向,將參數傳遞給Swift的spa
webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType)3d
捕獲到頁面定向後分析參數,讀取到img的src,彈出保存對話框
代碼
enum TouchState { case None case Start case Move case End case Cancel }
//腳本觸摸事件 static var touchJSStr:String = "document.ontouchstart=function(event){x=event.targetTouches[0].clientX;y=event.targetTouches[0].clientY;document.location=\"myweb:touch:start:\"+x+\":\"+y;};document.ontouchmove=function(event){x=event.targetTouches[0].clientX;y=event.targetTouches[0].clientY;document.location=\"myweb:touch:move:\"+x+\":\"+y;};document.ontouchcancel=function(event){document.location=\"myweb:touch:cancel\";};document.ontouchend=function(event){document.location=\"myweb:touch:end\";};"
static var imgUrl:String = ""//存儲當前點擊的圖片路徑 var touchState:TouchState = TouchState.None//設置默認的點擊狀態爲NONE var timer:NSTimer? = nil//定時器 長按時 定時器啓動 執行一次 彈出保存確認
ViewController要繼承UIWebViewDelegate,UIActionSheetDelegate
@IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() webView.delegate = self webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://image.baidu.com")!)) }
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{ let requestStr:String = request.URL!.absoluteString let components = requestStr.componentsSeparatedByString(":") if(components.count>1 && components[0] == "myweb"){ if(components[1] == "touch"){ if(components[2] == "start"){ touchState = TouchState.Start let ptX:Float32 = (components[3] as NSString).floatValue let ptY:Float32 = (components[4] as NSString).floatValue let js:String = "document.elementFromPoint(\(ptX), \(ptY)).tagName" let tagName:String? = webView.stringByEvaluatingJavaScriptFromString(js) if(tagName!.uppercaseString == "IMG") { let srcJS:String = "document.elementFromPoint(\(ptX), \(ptY)).src" ViewController.imgUrl = srcJS if(ViewController.imgUrl != ""){ timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "handleLongTouch", userInfo: nil, repeats: false) } } }else if(components[2] == "move"){ touchState = TouchState.Move if(timer != nil) { timer!.fire() } } else if(components[2] == "cancel"){ touchState = TouchState.Cancel if(timer != nil) { timer!.fire() } } else if(components[2] == "end"){ touchState = TouchState.End if(timer != nil) { timer!.fire() } } } } return true } func webViewDidFinishLoad(webView: UIWebView){ webView.stringByEvaluatingJavaScriptFromString(ViewController.touchJSStr)//觸摸js註冊 } //彈出保存對話框 func handleLongTouch(){ if(ViewController.imgUrl != "" && touchState == TouchState.Start){ var sheet:UIActionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "保存圖片") sheet.cancelButtonIndex = sheet.numberOfButtons - 1 sheet.showInView(UIApplication.sharedApplication().keyWindow!) } } //按鈕點擊保存 保存圖片 須要實現 UIActionSheetDelegate func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int){ if(buttonIndex == 1){ let urlToSave:String? = self.webView.stringByEvaluatingJavaScriptFromString(ViewController.imgUrl) let data:NSData? = NSData(contentsOfURL: NSURL(string: urlToSave!)!) var image:UIImage? = UIImage(data: data!) UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil) } } func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) { if didFinishSavingWithError != nil { return } }