且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

【iOS开发】自动识别剪贴板内容

更新时间:2022-10-09 19:01:52

之前用淘宝给微信好友分享链接的时候,发现在微信中复制了宝贝的链接,然后再从后台切换到淘宝客户端,淘宝就会弹出一个页面,询问是否要跳转到相关页面,今天试着实现了一下,分享出来~

    //识别剪贴板中的内容
    if let paste = UIPasteboard.generalPasteboard().string where
        (paste.hasPrefix("http://") || paste.hasPrefix("https://")) { 
        //如果剪贴板中的内容是链接
        let alert = UIAlertController(title: "要打开剪贴板中的链接吗?",
            message: nil,
            preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "打开",
            style: UIAlertActionStyle.Default,
            handler: { Void in
                // your implementation
                print(paste)
        }))
        alert.addAction(UIAlertAction(title: "忽略",
            style: UIAlertActionStyle.Cancel,
            handler: nil))
        //弹出Alert
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        if let vc = storyboard.instantiateViewControllerWithIdentifier("navi") as? UINavigationController {
            self.window?.rootViewController = vc
            vc.presentViewController(alert, animated: true, completion: nil)
        }
    }

获取设备的剪贴板很简单,第一行代码就搞定了,if 语句中判断了一下剪贴板中的内容是不是链接,注意http和https都要写上,这点很容易被忽略(在浏览器地址栏中复制以www.开头的文本会自动在剪贴板中转为http或https开头的链接)。

更值得注意的是,因为你需要让 App 在每次从后台进入前台的时候都检测一下剪贴板中有没有链接,所以以上方法要放在 AppDelegate 文件的 applicationWillEnterForeground 方法中。

AppDelegate.swift

而这个方法中是不能通过 self 来调用 ViewController 的,所以要曲线救国的话,你需要手动获取 Storyboard、ViewController,再设置window的rootViewController 才能去掉所有报错和警告。

(这里我只是把剪贴板中的链接输出到控制台了,想要自己用 UIWebView 打开链接的话,在// your implementation 这句注释这里写自己的方法吧)


【150928 更新】

对比 applicationWillEnterForeground
applicationDidBecomeActive
这两个方法,前者是指 App从后台进入前台,后者是指 App处于活跃状态,所以前者相对于后者,缺少的部分是,当 App 刚刚启动,而不是从后台取出的时候,它无法识别剪贴板。
因为你不能要求每次都让用户先把 App 打开,再往剪贴板里面填东西,再跳转回来,所以个人建议把上面的代码放在 applicationDidBecomeActive 方法中,而不是 applicationWillEnterForeground