2011-01-31 134 views
7

編輯:問題已解決。爲了向社區貢獻一點,我設置了一些幫助程序方法和一個示例,說明如何在我的博客上使用它們。在此查找KeyChain MT example使用Monotouch存儲和讀取密碼鑰匙密碼

- 原題:

在模擬器和iPad上運行的iOS4.2。

我正試圖使用​​下面的代碼存儲和讀取鑰匙串密碼。我的代碼靈感是https://github.com/ldandersen/scifihifi-iphone/,但我無法實現它的工作。我錯過了什麼?

// Create a record. 
SecRecord o = new SecRecord (SecKind.GenericPassword); 
o.Service = "myService"; 
o.Label = "myService"; 
o.Account = "[email protected]"; 
// The super secret password. 
o.Generic = NSData.FromString ("secret!", NSStringEncoding.UTF8); 
// Add to keychain. 
SecKeyChain.Add (o); 

// Now cerate another recored to query what we just saved. 
o = new SecRecord (SecKind.GenericPassword); 
o.Service = "myService"; 
o.Account = "[email protected]"; 

// Query as record.   
SecStatusCode code; 
var data = SecKeyChain.QueryAsRecord (o, out code); 

// This will tell us "all good!"... 
Console.WriteLine (code); 

// But data.Generic is NULL and this line will crash. :-(
Console.WriteLine (NSString.FromData (data.Generic, NSStringEncoding.UTF8)); 
+0

好博客文章,非常有用,謝謝! – vlad259 2011-02-02 14:27:01

+0

這仍然是公認的方法嗎? – servarevitas3 2012-12-18 15:56:16

回答

5

而不是使用SecRecord.ValueData嘗試這個辦法:從那裏SecKind.GenericPassword

Console.WriteLine(NSString.FromData(data.Generic, NSStringEncoding.ASCIIStringEncoding)); 

Generic回報的NSData的存儲。