使用Swift查询iOS Keychain [英] Querying iOS Keychain using Swift

查看:218
本文介绍了使用Swift查询iOS Keychain的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Swift转换Keychain查询结果。

I'm stuck converting the Keychain query result using Swift.

我的请求似乎有效:

let queryAttributes = NSDictionary(objects: [kSecClassGenericPassword, "MyService",     "MyAccount",       true],
                                   forKeys: [kSecClass,                kSecAttrService, kSecAttrAccount, kSecReturnData])


dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    var dataTypeRef : Unmanaged<AnyObject>?
    let status = SecItemCopyMatching(queryAttributes, &dataTypeRef);

    let retrievedData : NSData = dataTypeRef!.takeRetainedValue() as NSData
    *** ^^^^can't compile this line^^^^
})

我的问题是,代码无法编译:

My problem is, code won't compile:

Bitcast requires both operands to be pointer or neither
  %114 = bitcast %objc_object* %113 to %PSs9AnyObject_, !dbg !487
Bitcast requires both operands to be pointer or neither
  %115 = bitcast %PSs9AnyObject_ %114 to i8*, !dbg !487
LLVM ERROR: Broken function found, compilation aborted!

我不知道如何转换 Unmanaged< AnyObject> NSData

有什么想法吗?

推荐答案

使用 withUnsafeMutablePointer 函数和 UnsafeMutablePointer struct来检索数据,如下所示:

Use withUnsafeMutablePointer function and UnsafeMutablePointer struct to retrieving the data, such as the following:

var result: AnyObject?
var status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(queryAttributes, UnsafeMutablePointer($0)) }

if status == errSecSuccess {
    if let data = result as NSData? {
        if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
            // ...
        }
    }
}

它在发布(最快[-O])版本时效果很好。

it works fine with release (Fastest [-O]) build.

这篇关于使用Swift查询iOS Keychain的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆