两个应用程序之间的钥匙串共享

Keychain sharing between two apps

Apple 提供了用 Swift 编写的通用钥匙串示例,我想继续使用 Objective-C。

我在两个应用程序和 canOpenUrl 上都启用了钥匙串共享我可以从 A 调用应用程序 B,现在我想将用户名和密码从应用程序 A 共享到应用程序 B。两个应用程序的应用程序 ID 相同.

看了各种教程也不想用第三方项目。 不知道如何将参数从应用程序 A 传递到应用程序 B。

第 1 步:
设置 URL Schemes 并将 AppAURL Scheme 添加到AppBinfo.plist 像这样:<key>LSApplicationQueriesSchemes</key> <array> <string>Aapp_Scheme</string> </array>

第 2 步:
在应用程序 A 中:

let url = URL.init(string: "B_Scheme://name=Obama&password=Trump");
    if UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url, options: ["":""], completionHandler: nil);
    }

第 3 步:
在应用程序 B 的 AppDelegate.swift 添加代码:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    var name  = "", password = "";
    let param = url.absoluteString.replacingOccurrences(of: "B_Scheme://", with: "");
    let paramArray = param.components(separatedBy: "&");
    for temp in paramArray {
        if (temp.range(of: "name=") != nil){
            name = temp.replacingOccurrences(of: "name=", with: "");
        }
        else if (temp.range(of: "password=") != nil){
            password = temp.replacingOccurrences(of: "password=", with: "");
        }
    }
    if name == "Obama" && password == "Trump" {
        print("get param success!");
    }
    return true;
}

启用钥匙串共享:

  1. 开启钥匙串共享功能。
  2. Select 开发团队
  3. 将钥匙串组名称指定为有意义的名称(例如 testKeychainG1)
  4. 打开 .entitlements 文件并将 $(AppIdentifierPrefix) 替换为您的 APP ID(例如 AB123CDE45.testKeychainG1)

访问钥匙串(检索共享项目):

let itemKey = "Item Key"

let keychainAccessGroupName = "AB123CDE45.testKeychainG1"


let query:[String:Any] = [
    kSecClass as String: kSecClassGenericPassword,
    kSecAttrAccount as String: itemKey,
    kSecReturnData as String: kCFBooleanTrue,
    kSecMatchLimit as String: kSecMatchLimitOne,
    kSecAttrAccessGroup as String: keychainAccessGroupName
]

var result: AnyObject?

let resultCodeLoad = withUnsafeMutablePointer(to: &result) {
    SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer([=10=]))
}

if resultCodeLoad == noErr {
    if let result = result as? Data,
        let keyValue = NSString(data: result,
                                encoding: String.Encoding.utf8.rawValue) as? String {

        // Found successfully
        print(keyValue)
    }
} else {
    print("Error: \(resultCodeLoad)")
}