This function writes to the keychain properly when testing on both the simulator and the device. It does not work when installed with an enterprise Signing Identity.
It is worth mentioning Keychain Sharing is enabled in the app and the app's extension.
Please note it works perfectly on the device when building with the development profile.
Additionally no errors are logged in the operation (see below) so there isn't any information as to why it failed.
public class func setToken(token: String, account: String, service: String = "APIrev1") {
var log = XCGLogger.defaultInstance()
log.info("Attempting to set token \(token) to account \(account)")
var secret: NSData = token.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let objects: Array = [secClassGenericPassword(), service, account, secret]
let keys: Array = [secClass(), secAttrService(), secAttrAccount(), secValueData()]
let query = NSDictionary(objects: objects, forKeys: keys)
var p1 = SecItemDelete(query as CFDictionaryRef)
if (p1 != noErr) {
log.info("SecItemDelete, key not present to delete")
}
var p2 = SecItemAdd(query as CFDictionaryRef, nil)
if (p2 != noErr) {
log.error("SecItemAdd write of token \(token) to account \(account) failed")
}
}