iOS app 與 Safari共享數據

公司要作 app 推廣渠道統計,因而調研了一下幾個方案javascript

方案選擇

一、使用SFSafariViewController(ios9 ~ ios10如下)、SFAuthenticationSession(ios11)、ASWebAuthenticationSession(ios12.0)來獲取safari內的cookie,但SFAuthenticationSession是OC語言的一個管理類,不能去除彈框,不能改變打開的H5頁面大小和禁止跳轉頁面java

二、匹對IP、userAgent等設備信息 等數據來達到確認渠道方的這一方案,由於IP地址可能會變更因此在匹對數據上會有偏差,ios

四、使用剪切板來匹對渠道源,當用戶在下載APP包的過程當中,用戶拷貝和剪切了其餘數據的狀況下,是沒法匹對渠道源的。並且只支持 iOS10+。iOS9 及一下js不支持。swift

測試 代碼

swift 代碼

import UIKit
import SafariServices
import AuthenticationServices // iOS 12+

class PopularizeUtil: NSObject {
    static private let URLString = ""
    private weak var rootVC: UIViewController?
    
    private func getPopularizeParmasBelowIOS10() {
        guard let url = URL(string: PopularizeUtil.URLString) else { return }
        //SFSafariViewController, 經過 open scheme 的方式回調,在UIApplicationDelegate 的 openUrl 裏面
        let vc = SFSafariViewController(url: url)
        vc.modalPresentationStyle = .overCurrentContext
        vc.delegate = self
        vc.view.alpha = 0 // fot test
        let rootVC = UIApplication.shared.windows.first?.rootViewController
        rootVC?.present(vc, animated: true, completion: {
            
        })
        self.rootVC = rootVC
    }
    
    private var iOS11Auth: Any?
    @available(iOS 11.0, *)
    private func getPopularizeParmasWithIOS11() {
        guard let url = URL(string: PopularizeUtil.URLString) else { return }
        let auth = SFAuthenticationSession(url: url, callbackURLScheme: "aaaa") { (url, error) in
            print("@@@@@@@@@@@@@ SFAuthenticationSession callback\(String(describing: url)),\(String(describing: error))")
            if let u = url?.absoluteString {
                NHAlertView.showNHAlertTitle("SFAuthenticationSession get cookie", message: u)
            }
        }
        auth.start()
        iOS11Auth = auth
    }

    
    private var iOS12Auth: Any?
    @available(iOS 12.0, *)
    private func getPopularizeParmasUpIOS12() {
        guard let url = URL(string: PopularizeUtil.URLString) else { return }
        let auth = ASWebAuthenticationSession(url: url, callbackURLScheme: "aaaa") { (url, error) in
            print("!!!!!! ASWebAuthenticationSession callback\(String(describing: url)),\(String(describing: error))")
            if let u = url?.absoluteString {
                NHAlertView.showNHAlertTitle("ASWebAuthenticationSession get cookie", message: u)
            }
        }
        auth.start()
        iOS12Auth = auth
    }
    
    
    private func getPopularizeParamsFromPasteboard() {
        let pasteboard = UIPasteboard.general
        print("字符串數據\(String(describing: pasteboard.string))")
        print("字符串數組\(String(describing: pasteboard.strings))")
        print("URL數據\(String(describing: pasteboard.url))")
        print("URL數組\(String(describing: pasteboard.urls))")
        if let str = pasteboard.string {
            NHAlertView.showNHAlertTitle(" UIPasteboard get data", message: str)
        }
    }
    
    @objc func getPopularizeParmas() {
        // by cookie
        if #available(iOS 12.0, *) {
            getPopularizeParmasUpIOS12()
        } else if #available(iOS 11.0, *) {
            getPopularizeParmasWithIOS11()
        } else {
            getPopularizeParmasBelowIOS10()
        }
        
        // by clipboard
//        getPopularizeParamsFromPasteboard()
    }
}

extension PopularizeUtil: SFSafariViewControllerDelegate {
    
    // 開始加載
    func safariViewController(_ controller: SFSafariViewController, initialLoadDidRedirectTo URL: URL) {
        print(" SFSafariViewController initialLoadDidRedirectTo:\(URL)")
    }
    // 頁面加載完成。只有初始URL加載完成時會調用。
    func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
        print(" SFSafariViewController didCompleteInitialLoad:\(didLoadSuccessfully)")
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
            self.rootVC?.dismiss(animated: true, completion: {

            })
        }
    }
    // 銷燬controller
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        print(" SFSafariViewController safariViewControllerDidFinish:\(controller)")
    }
}
複製代碼

共享 cookie

<<head>
  <meta name="viewport" content="width=device-width">
</head>

<body>
<script>

var c = document.cookie;
var m = c.match(/name=(\w+)/);
var name;

if (m) {
  document.writeln("You are " + m[1] + '.');
  name = m[1];
} else {
  document.writeln("You are anonymous.");
  name = "";
}


if (name) {
	alert(name);
	var Schemes = "aaaa"
    if (name.length > 0) {
        location.href = Schemes+"://testcookie/" + name;
    } else  {
        location.href = Schemes+"://";
    }
}

function saveName() {
    document.cookie = 'name=' + document.getElementById('name').value + ';max-age=3600';
    location.reload();
}

</script>

<input type="text" id="name">
<input type="submit" value="Save" onclick="saveName();">

</body>
複製代碼

測試 clipboard 代碼

<head>
  <meta name="viewport" content="width=device-width">
</head>

<body>
<script>
function copyData() {
    var copy = function (e) {
        e.preventDefault();
        console.log('copy');
        var text = "blabla"
        if (e.clipboardData) {
          e.clipboardData.setData('text/plain', text);
        } else if (window.clipboardData) {
          window.clipboardData.setData('Text', text);
        }
    }
    window.addEventListener('copy', copy);
    document.execCommand('copy');
    window.removeEventListener('copy', copy);
}

function copyData2(text) {
  const input = document.createElement('input');
  input.setAttribute('readonly', 'readonly');
  input.setAttribute('value', text);
  document.body.appendChild(input);
  input.setSelectionRange(0, 9999);
  if (document.execCommand('copy')) {
    document.execCommand('copy');
    console.log('複製成功');
  }
    document.body.removeChild(input);
}

function saveName() {
  var text = document.getElementById('name').value
  copyData2(text);
}

</script>

<input type="text" id="name">
<input type="submit" value="Save" onclick="saveName();">

</body>
複製代碼

參考連接

blog.csdn.net/jiang314/ar… blog.csdn.net/u014410695/… www.jianshu.com/p/6cb411f04… www.jianshu.com/p/81150f7e6… www.jianshu.com/p/d2ce1d97b… stackoverflow.com/questions/3…windows

juejin.im/post/5aefeb… juejin.im/post/5a94f8…數組

相關文章
相關標籤/搜索