在使用
Swift的Xcode 6和7的早期版本中,这种语法可以工作:
var secureItemValue: Unmanaged<AnyObject>? let statusCode: OSStatus = SecItemCopyMatching(keychainItemQuery,&secureItemValue) if statusCode == errSecSuccess { let opaquePointer = secureItemValue?.toOpaque() let secureItemValueData = Unmanaged<NSData>.fromOpaque(opaquePointer!).takeUnretainedValue() // Use secureItemValueData... }
但是,在Xcode 7 beta 4中,SecItemCopyMatching声明已更改:
OLD:func SecItemCopyMatching(_ query:CFDictionary,_ result:UnsafeMutablePointer< AnyObject?>) – > OSStatus
新:func SecItemCopyMatching(_ query:CFDictionary!,_ result:UnsafeMutablePointer< Unmanaged< AnyObject>?>) – > OSStatus
…现在secureItemValue类型不匹配.
在提取结果之前,这个机制很混乱,我希望新声明在某种程度上更容易,但我不知道如何为secureItemValue变量声明正确的类型并提取结果.
解决方法
这适用于Xcode 7 beta 4
var dataTypeRef: AnyObject? let status: OSStatus = withUnsafeMutablePointer(&dataTypeRef) { SecItemCopyMatching(keychainQuery as CFDictionaryRef,UnsafeMutablePointer($0)) } if status == noErr { return dataTypeRef as? NSData } else { return nil }