SFHFKeychainUtils. iOS keychain. ARC compatible - iphone

I was wondering if anyone that was using the SFHFKeychainUtils managed to modify them to be compatible for ARC. More exactly the
NSDictionary *attributeResult = NULL;
NSMutableDictionary *attributeQuery = [query mutableCopy];
[attributeQuery setObject: (id) kCFBooleanTrue forKey:(__bridge id) kSecReturnAttributes];
OSStatus status = SecItemCopyMatching((CFDictionaryRef) attributeQuery,(CFTypeRef *)(attributeResult));
I tried
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef) attributeQuery,(CFTypeRef *)(attributeResult));
also
CFTypeRef subAttributeResult = (CFTypeRef *)(objc_unretainedPointer(attributeResult));
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef) attributeQuery,(CFTypeRef *)(subAttributeResult));
These 2 being the only 2 approaches I managed to get no errors for. Any other approach by adding objc_XXX instead of CFTypeRef here and there gets me errors(from implicit conversions from obj-c pointer to CFTypeRef is disallowed in ARC, to passing x parameter to y parameter discards qualifiers). Obviously the first snip of code gives an error too. Although I get no errors when building, app crashes with EXC_BAD_ACCESS when reaching this part of code.
The link for the full SFHFKeychainUtils: https://github.com/ldandersen/scifihifi-iphone/tree/master/security
Any help, please?
Thank you.

here is the ARC compatible SFHFKeychainUtils,
SFHFKeychainUtils.h
//
// SFHFKeychainUtils.h
//
// Created by Buzz Andersen on 10/20/08.
// Based partly on code by Jonathan Wight, Jon Crosby, and Mike Malone.
// Copyright 2008 Sci-Fi Hi-Fi. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#import <UIKit/UIKit.h>
#interface SFHFKeychainUtils : NSObject {
}
+ (NSString *) getPasswordForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error;
+ (BOOL) storeUsername: (NSString *) username andPassword: (NSString *) password forServiceName: (NSString *) serviceName updateExisting: (BOOL) updateExisting error: (NSError **) error;
+ (BOOL) deleteItemForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error;
#end
SFHFKeychainUtils.m
//
// SFHFKeychainUtils.m
//
// Created by Buzz Andersen on 10/20/08.
// Based partly on code by Jonathan Wight, Jon Crosby, and Mike Malone.
// Copyright 2008 Sci-Fi Hi-Fi. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#import "SFHFKeychainUtils.h"
#import <Security/Security.h>
static NSString *SFHFKeychainUtilsErrorDomain = #"SFHFKeychainUtilsErrorDomain";
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 30000 && TARGET_IPHONE_SIMULATOR
#interface SFHFKeychainUtils (PrivateMethods)
(SecKeychainItemRef) getKeychainItemReferenceForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error;
#end
#endif
#implementation SFHFKeychainUtils
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 30000 && TARGET_IPHONE_SIMULATOR
+(NSString *) getPasswordForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error {
if (!username || !serviceName) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: -2000 userInfo: nil];
return nil;
}
SecKeychainItemRef item = [SFHFKeychainUtils getKeychainItemReferenceForUsername: username andServiceName: serviceName error: error];
if (*error || !item) {
return nil;
}
// from Advanced Mac OS X Programming, ch. 16
UInt32 length;
char *password;
SecKeychainAttribute attributes[8];
SecKeychainAttributeList list;
attributes[0].tag = kSecAccountItemAttr;
attributes[1].tag = kSecDescriptionItemAttr;
attributes[2].tag = kSecLabelItemAttr;
attributes[3].tag = kSecModDateItemAttr;
list.count = 4;
list.attr = attributes;
OSStatus status = SecKeychainItemCopyContent(item, NULL, &list, &length, (void **)&password);
if (status != noErr) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: status userInfo: nil];
return nil;
}
NSString *passwordString = nil;
if (password != NULL) {
char passwordBuffer[1024];
if (length > 1023) {
length = 1023;
}
strncpy(passwordBuffer, password, length);
passwordBuffer[length] = '\0';
passwordString = [NSString stringWithCString:passwordBuffer];
}
SecKeychainItemFreeContent(&list, password);
CFRelease(item);
return passwordString;
}
+ (void) storeUsername: (NSString *) username andPassword: (NSString *) password forServiceName: (NSString *) serviceName updateExisting: (BOOL) updateExisting error: (NSError **) error {
if (!username || !password || !serviceName) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: -2000 userInfo: nil];
return;
}
OSStatus status = noErr;
SecKeychainItemRef item = [SFHFKeychainUtils getKeychainItemReferenceForUsername: username andServiceName: serviceName error: error];
if (*error && [*error code] != noErr) {
return;
}
*error = nil;
if (item) {
status = SecKeychainItemModifyAttributesAndData(item,NULL,strlen([password UTF8String]),[password UTF8String]);
CFRelease(item);
}
else {
status = SecKeychainAddGenericPassword(NULL,strlen([serviceName UTF8String]),[serviceName UTF8String],strlen([username UTF8String]),[username UTF8String],strlen([password UTF8String]),[password UTF8String],NULL);
}
if (status != noErr) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: status userInfo: nil];
}
}
+ (void) deleteItemForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error {
if (!username || !serviceName) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: 2000 userInfo: nil];
return;
}
*error = nil;
SecKeychainItemRef item = [SFHFKeychainUtils getKeychainItemReferenceForUsername: username andServiceName: serviceName error: error];
if (*error && [*error code] != noErr) {
return;
}
OSStatus status;
if (item) {
status = SecKeychainItemDelete(item);
CFRelease(item);
}
if (status != noErr) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: status userInfo: nil];
}
}
+ (SecKeychainItemRef) getKeychainItemReferenceForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error {
if (!username || !serviceName) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: -2000 userInfo: nil];
return nil;
}
*error = nil;
SecKeychainItemRef item;
OSStatus status = SecKeychainFindGenericPassword(NULL,strlen([serviceName UTF8String]),[serviceName UTF8String],strlen([username UTF8String]),[username UTF8String], NULL,NULL,&item);
if (status != noErr) {
if (status != errSecItemNotFound) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: status userInfo: nil];
}
return nil;
}
return item;
}
#else
+ (NSString *) getPasswordForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error {
if (!username || !serviceName) {
if (error != nil) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: -2000 userInfo: nil];
}
return nil;
}
if (error != nil) {
*error = nil;
}
// Set up a query dictionary with the base query attributes: item type (generic), username, and service
NSArray *keys = [[NSArray alloc] initWithObjects: (__bridge_transfer NSString *) kSecClass, kSecAttrAccount, kSecAttrService, nil];
NSArray *objects = [[NSArray alloc] initWithObjects: (__bridge_transfer NSString *) kSecClassGenericPassword, username, serviceName, nil];
NSMutableDictionary *query = [[NSMutableDictionary alloc] initWithObjects: objects forKeys: keys];
// First do a query for attributes, in case we already have a Keychain item with no password data set.
// One likely way such an incorrect item could have come about is due to the previous (incorrect)
// version of this code (which set the password as a generic attribute instead of password data).
NSMutableDictionary *attributeQuery = [query mutableCopy];
[attributeQuery setObject: (id) kCFBooleanTrue forKey:(__bridge_transfer id) kSecReturnAttributes];
CFTypeRef attrResult = NULL;
OSStatus status = SecItemCopyMatching((__bridge_retained CFDictionaryRef) attributeQuery, &attrResult);
//NSDictionary *attributeResult = (__bridge_transfer NSDictionary *)attrResult;
if (status != noErr) {
// No existing item found--simply return nil for the password
if (error != nil && status != errSecItemNotFound) {
//Only return an error if a real exception happened--not simply for "not found."
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: status userInfo: nil];
}
return nil;
}
// We have an existing item, now query for the password data associated with it.
NSMutableDictionary *passwordQuery = [query mutableCopy];
[passwordQuery setObject: (id) kCFBooleanTrue forKey: (__bridge_transfer id) kSecReturnData];
CFTypeRef resData = NULL;
status = SecItemCopyMatching((__bridge_retained CFDictionaryRef) passwordQuery, (CFTypeRef *) &resData);
NSData *resultData = (__bridge_transfer NSData *)resData;
if (status != noErr) {
if (status == errSecItemNotFound) {
// We found attributes for the item previously, but no password now, so return a special error.
// Users of this API will probably want to detect this error and prompt the user to
// re-enter their credentials. When you attempt to store the re-entered credentials
// using storeUsername:andPassword:forServiceName:updateExisting:error
// the old, incorrect entry will be deleted and a new one with a properly encrypted
// password will be added.
if (error != nil) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: -1999 userInfo: nil];
}
}
else {
// Something else went wrong. Simply return the normal Keychain API error code.
if (error != nil) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: status userInfo: nil];
}
}
return nil;
}
NSString *password = nil;
if (resultData) {
password = [[NSString alloc] initWithData: resultData encoding: NSUTF8StringEncoding];
}
else {
// There is an existing item, but we weren't able to get password data for it for some reason,
// Possibly as a result of an item being incorrectly entered by the previous code.
// Set the -1999 error so the code above us can prompt the user again.
if (error != nil) {
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: -1999 userInfo: nil];
}
}
return password;
}
+ (BOOL) storeUsername: (NSString *) username andPassword: (NSString *) password forServiceName: (NSString *) serviceName updateExisting: (BOOL) updateExisting error: (NSError **) error
{
if (!username || !password || !serviceName)
{
if (error != nil)
{
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: -2000 userInfo: nil];
}
return NO;
}
// See if we already have a password entered for these credentials.
NSError *getError = nil;
NSString *existingPassword = [SFHFKeychainUtils getPasswordForUsername: username andServiceName: serviceName error:&getError];
if ([getError code] == -1999)
{
// There is an existing entry without a password properly stored (possibly as a result of the previous incorrect version of this code.
// Delete the existing item before moving on entering a correct one.
getError = nil;
[self deleteItemForUsername: username andServiceName: serviceName error: &getError];
if ([getError code] != noErr)
{
if (error != nil)
{
*error = getError;
}
return NO;
}
}
else if ([getError code] != noErr)
{
if (error != nil)
{
*error = getError;
}
return NO;
}
if (error != nil)
{
*error = nil;
}
OSStatus status = noErr;
if (existingPassword)
{
// We have an existing, properly entered item with a password.
// Update the existing item.
if (![existingPassword isEqualToString:password] && updateExisting)
{
//Only update if we're allowed to update existing. If not, simply do nothing.
NSArray *keys = [[NSArray alloc] initWithObjects: (__bridge_transfer NSString *) kSecClass,kSecAttrService,kSecAttrLabel,kSecAttrAccount,nil];
NSArray *objects = [[NSArray alloc] initWithObjects: (__bridge_transfer NSString *) kSecClassGenericPassword,serviceName,serviceName,username,nil];
NSDictionary *query = [[NSDictionary alloc] initWithObjects: objects forKeys: keys];
status = SecItemUpdate((__bridge_retained CFDictionaryRef) query, (__bridge_retained CFDictionaryRef) [NSDictionary dictionaryWithObject: [password dataUsingEncoding: NSUTF8StringEncoding] forKey: (__bridge_transfer NSString *) kSecValueData]);
}
}
else
{
// No existing entry (or an existing, improperly entered, and therefore now
// deleted, entry). Create a new entry.
NSArray *keys = [[NSArray alloc] initWithObjects: (__bridge_transfer NSString *) kSecClass,kSecAttrService,kSecAttrLabel,kSecAttrAccount,kSecValueData,nil];
NSArray *objects = [[NSArray alloc] initWithObjects: (__bridge_transfer NSString *) kSecClassGenericPassword,serviceName,serviceName,username,[password dataUsingEncoding: NSUTF8StringEncoding],nil];
NSDictionary *query = [[NSDictionary alloc] initWithObjects: objects forKeys: keys];
status = SecItemAdd((__bridge_retained CFDictionaryRef) query, NULL);
}
if (error != nil && status != noErr)
{
// Something went wrong with adding the new item. Return the Keychain error code.
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: status userInfo: nil];
return NO;
}
return YES;
}
+ (BOOL) deleteItemForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error
{
if (!username || !serviceName)
{
if (error != nil)
{
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: -2000 userInfo: nil];
}
return NO;
}
if (error != nil)
{
*error = nil;
}
NSArray *keys = [[NSArray alloc] initWithObjects: (__bridge_transfer NSString *) kSecClass, kSecAttrAccount, kSecAttrService, kSecReturnAttributes, nil];
NSArray *objects = [[NSArray alloc] initWithObjects: (__bridge_transfer NSString *) kSecClassGenericPassword, username, serviceName, kCFBooleanTrue, nil];
NSDictionary *query = [[NSDictionary alloc] initWithObjects: objects forKeys: keys];
OSStatus status = SecItemDelete((__bridge_retained CFDictionaryRef) query);
if (error != nil && status != noErr)
{
*error = [NSError errorWithDomain: SFHFKeychainUtilsErrorDomain code: status userInfo: nil];
return NO;
}
return YES;
}
#endif
#end

I had the same issue - and don't know who properly to credit this to - but the version of SFHFKeychainUtils in this github project works with ARC as a drop in replacement.

In case anybody lands on this page with the same question, I would recommend you have a look at Sam Soffes SSKeychain component.
Not only is it ARC compatible, its well documented, maintained and has more features than SFHFKeychainUtils.

You can always make that one file non-ARC.

I just moved another framework (MPOAuth) to ARC, this is how I solved this issue:
NSString *foundPassword = nil;
NSData *foundValue = nil;
CFTypeRef foundDict;
status = SecItemCopyMatching((__bridge CFDictionaryRef)attributeQuery, &foundDict);
if (status == noErr) {
attributesDictionary = (__bridge_transfer NSDictionary *)foundDict;
foundValue = [attributesDictionary objectForKey:(__bridge id)kSecValueData];
if (foundValue) {
foundPassword = [[NSString alloc] initWithData:foundValue
encoding:NSUTF8StringEncoding];
}
}
I'll have to verify whether this causes foundDict to leak or not..

See this question:
iPhone fetch data dictionary from keychain
I haven't tested it yet, but it sounds right. You won't need to disable ARC. It also has notes on how to get rid of the
Cast of an indirect pointer to an Objective-C pointer to 'CFTypeRef*'
(aka 'const void**') is disallowed with ARC.
error.

The developer specifically mentions in his Github page that SFHFKeychainUtils should be considered deprecated, and to look at STKeychain instead in STUtils:
https://github.com/ldandersen/STUtils/tree/master/Security

Related

Javascript Youtube API: buffering for ever - UIWebView iOS

I am using the YouTube API in UIWebView.
I have created a NSString with the HTML5 player that I load in the UIWebView. Everything works perfectly on iPhone 5 and iPad.
But, if I test the app using an iPhone 4, the player returns the buffering state all the time. Only if I explicitly press the play button, the player starts playing, without stopping again for buffering. It seems that although the video has been buffered, the player still gives me this state.
Is anyone aware of this problem? Any idea?
Thank you very much in advance!!
In LBYouTubePlayerViewController.m file
Replace Following method on yr old Method....
then test...
-(NSURL*)_extractYouTubeURLFromFile:(NSString *)html error:(NSError *__autoreleasing *)error {
NSString *JSONStart = nil;
// NSString *JSONStartFull = #"ls.setItem('PIGGYBACK_DATA', \")]}'";
NSString *JSONStartFull = #"bootstrap_data = \")]}'";
NSString *JSONStartShrunk = [JSONStartFull stringByReplacingOccurrencesOfString:#" " withString:#""];
if ([html rangeOfString:JSONStartFull].location != NSNotFound)
JSONStart = JSONStartFull;
else if ([html rangeOfString:JSONStartShrunk].location != NSNotFound)
JSONStart = JSONStartShrunk;
if (JSONStart != nil) {
NSScanner* scanner = [NSScanner scannerWithString:html];
[scanner scanUpToString:JSONStart intoString:nil];
[scanner scanString:JSONStart intoString:nil];
NSString *JSON = nil;
[scanner scanUpToString:#"}\";" intoString:&JSON];
JSON = [NSString stringWithFormat:#"%#}",JSON]; // Add closing bracket } to get vallid JSON again
// [scanner scanUpToString:#"\");" intoString:&JSON];
JSON = [self _unescapeString:JSON];
NSError* decodingError = nil;
NSDictionary* JSONCode = nil;
// First try to invoke NSJSONSerialization (Thanks Mattt Thompson)
id NSJSONSerializationClass = NSClassFromString(#"NSJSONSerialization");
SEL NSJSONSerializationSelector = NSSelectorFromString(#"dataWithJSONObject:options:error:");
if (NSJSONSerializationClass && [NSJSONSerializationClass respondsToSelector:NSJSONSerializationSelector]) {
JSONCode = [NSJSONSerialization JSONObjectWithData:[JSON dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&decodingError];
}
else {
JSONCode = [JSON objectFromJSONStringWithParseOptions:JKParseOptionNone error:&decodingError];
}
if (decodingError) {
// Failed
*error = decodingError;
}
else {
// Success
NSDictionary *dict = [JSONCode objectForKey:#"content"];
NSDictionary *dictTemp = [dict objectForKey:#"video"];
NSArray* videos = [dictTemp objectForKey:#"fmt_stream_map"];
NSString* streamURL = nil;
if (videos.count) {
NSString* streamURLKey = #"url";
if (self.quality == LBYouTubePlayerQualityLarge) {
streamURL = [[videos objectAtIndex:0] objectForKey:streamURLKey];
}
else if (self.quality == LBYouTubePlayerQualityMedium) {
unsigned int index = MAX(0, videos.count-2);
streamURL = [[videos objectAtIndex:index] objectForKey:streamURLKey];
}
else {
streamURL = [[videos lastObject] objectForKey:streamURLKey];
}
}
if (streamURL) {
return [NSURL URLWithString:streamURL];
}
else {
*error = [NSError errorWithDomain:kLBYouTubePlayerControllerErrorDomain code:2 userInfo:[NSDictionary dictionaryWithObject:#"Couldn't find the stream URL." forKey:NSLocalizedDescriptionKey]];
}
}
}
else {
*error = [NSError errorWithDomain:kLBYouTubePlayerControllerErrorDomain code:3 userInfo:[NSDictionary dictionaryWithObject:#"The JSON data could not be found." forKey:NSLocalizedDescriptionKey]];
}
return nil;
}

How do I get a list of the user's contacts in iOS 6?

I have been using the following code for a few years now and it has always worked, but it looks like with iOS 6 it doesn't anymore. How do I get a list of all contacts on an iOS 6 device?
ABAddressBookRef myAddressBook = ABAddressBookCreate();
NSMutableArray *people = (__bridge_transfer NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(myAddressBook);
CFRelease(myAddressBook);
// repeat through all contacts in the inital array we loaded
for(int i=0; i<[people count]; i++)
{
NSString *aName;
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:i]), kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:i]), kABPersonLastNameProperty);
if (([firstName isEqualToString:#""] || [firstName isEqualToString:#"(null)"] || firstName == nil) &&
([lastName isEqualToString:#""] || [lastName isEqualToString:#"(null)"] || lastName == nil))
{
// do nothing
}
else
{
aName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
if ([firstName isEqualToString:#""] || [firstName isEqualToString:#"(null)"] || firstName == nil)
{
aName = [NSString stringWithFormat:#"%#", lastName];
}
if ([lastName isEqualToString:#""] || [lastName isEqualToString:#"(null)"] || lastName == nil)
{
aName = [NSString stringWithFormat:#"%#", firstName];
}
[self.tableItems addObject:aName];
}
}
[self.tableItems sortUsingSelector:#selector(compare:)];
In ios6 you need to ask for permission to read the AddressBook, otherwise you'll get nil. Use something like this:
- (BOOL)askContactsPermission {
__block BOOL ret = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS6
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRef addressBook = ABAddressBookCreate();
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
ret = granted;
dispatch_semaphore_signal(sema);
});
if (addressBook) {
CFRelease(addressBook);
}
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release(sema);
}
else { // we're on iOS5 or older
ret = YES;
}
return ret;
}
If this method returns NO, bad luck, you won't be able to access the AB. I'm locking with a semaphore here because I don't want to continue with my app if the user does not allow the AB. There other methods, just check the API.
You do need to ask the user for permission which will trigger a prompt to the user when you do so. Here's another way to do this using execution blocks to handle the result, also makes the usage of it version agnostic if you need to query your current access status from common code.
I implement an access manager like so
AppContactsAccessManager.h
#import <AddressBook/AddressBook.h>
typedef enum
{
kABAuthStatusNotDetermined = 0,
kABAuthStatusRestricted,
kABAuthStatusDenied,
kABAuthStatusAuthorized,
kABAuthStatusPending,
}AddressBookAuthStatus;
typedef void (^AddressbookRequestHandler)(ABAddressBookRef addressBookRef, BOOL available);
#interface AppContactsAccessManager : NSObject
{
AddressBookAuthStatus status;
}
- (void) requestAddressBookWithCompletionHandler:(AddressbookRequestHandler)handler;
- (AddressBookAuthStatus) addressBookAuthLevel;
#end
AppContactsAccessManager.m
#implementation AppContactsAccessManager
- (BOOL) isStatusAvailable:(AddressBookAuthStatus)theStatus
{
return (theStatus == kABAuthStatusAuthorized || theStatus == kABAuthStatusRestricted);
}
- (void) requestAddressBookWithCompletionHandler:(AddressbookRequestHandler)handler
{
ABAddressBookRef addressBookRef = NULL;
if([self isiOS6]){
addressBookRef = ABAddressBookCreateWithOptions(nil, nil);
ABAuthorizationStatus curStatus = ABAddressBookGetAuthorizationStatus();
if(curStatus == kABAuthorizationStatusNotDetermined)
{
status = kABAuthStatusPending;
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
status = ABAddressBookGetAuthorizationStatus();
if(handler != NULL){
handler(addressBookRef, [self isStatusAvailable:status]);
}
});
}else
{
status = curStatus;
dispatch_async(dispatch_get_current_queue(), ^{
if(handler != NULL){
handler(addressBookRef, [self isStatusAvailable:status]);
}
});
}
}else
{
addressBookRef = ABAddressBookCreate();
status = kABAuthStatusAuthorized;
dispatch_async(dispatch_get_current_queue(), ^{
if(handler != NULL){
handler(addressBookRef, [self isStatusAvailable:status]);
}
});
}
}
- (AddressBookAuthStatus) addressBookAuthLevel
{
return status;
}
#end
usage would look something like:
AppContactsAccessManager* accessMgr = [AppContactsAccessManager new];
[accessMgr requestAddressBookWithCompletionHandler:^(ABAddressBookRef theAddressBookRef, BOOL available) {
// do your addressbook stuff in here
}];

Bug in MailCore when sending mail through bcc

When sending an email with receipts as following
to: personA
cc: personB
bcc :personC
All the three person will get the email. And all the received emails will display personC in the receipts field. As we know the bcc contacts personC should not be displayed. Why could this happen? I correctly set the CTCoreMessage with to, cc and bcc. Is this a bug of MailCore Framework? Or is there something i missed?
Thanks in advance!
The following is the related code for your reference
- (IBAction)buttonSendPressed:(id)sender
{
[self dismissViewControllerAnimated:YES completion:^{
CTCoreMessage *testMsg = [[CTCoreMessage alloc] init];
NSMutableArray *mutArrTos = [NSMutableArray array]; // personA
NSMutableArray *mutArrCcs = [NSMutableArray array]; // personB
NSMutableArray *mutArrBccs = [NSMutableArray array]; // personC
NSLog(#"toContactArr :%#",toContactArr);
if (toContactArr.count>0) {
for (NSDictionary *dict in toContactArr) {
[mutArrTos addObject:[CTCoreAddress addressWithName:[dict valueForKey:#"name"] email:[dict valueForKey:#"email"]]];
}
NSLog(#"mutArrRecipients : %#", mutArrTos);
[testMsg setTo:[NSSet setWithArray:mutArrTos]];
}
if (ccContactArr.count>0) {
for (NSDictionary *dict in ccContactArr) {
[mutArrCcs addObject:[CTCoreAddress addressWithName:[dict valueForKey:#"name"] email:[dict valueForKey:#"email"]]];
}
NSLog(#"mutArrRecipients : %#", mutArrCcs);
[testMsg setCc:[NSSet setWithArray:mutArrCcs]];
}
if (bccContactArr.count>0) {
for (NSDictionary *dict in bccContactArr) {
[mutArrBccs addObject:[CTCoreAddress addressWithName:[dict valueForKey:#"name"] email:[dict valueForKey:#"email"]]];
}
NSLog(#"mutArrRecipients : %#", mutArrBccs);
[testMsg setBcc:[NSSet setWithArray:mutArrBccs]];
}
[testMsg setFrom:[NSSet setWithObject:[CTCoreAddress addressWithName:#"222222" email:#"letibe.xx#gmail.com"]]];
[testMsg setBody:self.textView.text];
[testMsg setSubject:self.textField.text];
DbManager *dbManager = [[DbManager sharedManager] switchDBWithFileName:DBNAME];
User *user = [dbManager getAccount];
NSString *account = user.account;
NSString *pwd = user.password;
NSString *emailType = user.email_type;
NSLog(#"user: %#", user);
NSLog(#"account: %#", account);
NSLog(#"pwd: %#", pwd);
NSLog(#"emailType: %#", emailType);
NSError *error;
BOOL success = [CTSMTPConnection sendMessage:testMsg server:#"smtp.gmail.com" username:#"letibe.xx#gmail.com" password:#"222222" port:25 useTLS:YES useAuth:YES error:&error];
if (!success) {
// Present the error
NSLog(#"error: %#", error);
}else{
NSLog(#"CTSMTPConnection success");
}
}];
}
After reading the SMTP protocol. I have modified the CTCoreMessage.m to remove the bcc address in the header as following. Then the bcc address won't print in the receiver.
CTCoreMessage.m
- (NSString *)render {
CTMIME *msgPart = myParsedMIME;
if ([myParsedMIME isKindOfClass:[CTMIME_MessagePart class]]) {
/* It's a message part, so let's set it's fields */
struct mailimf_fields *fields;
struct mailimf_mailbox *sender = (myFields->fld_sender != NULL) ? (myFields->fld_sender->snd_mb) : NULL;
struct mailimf_mailbox_list *from = (myFields->fld_from != NULL) ? (myFields->fld_from->frm_mb_list) : NULL;
struct mailimf_address_list *replyTo = (myFields->fld_reply_to != NULL) ? (myFields->fld_reply_to->rt_addr_list) : NULL;
struct mailimf_address_list *to = (myFields->fld_to != NULL) ? (myFields->fld_to->to_addr_list) : NULL;
struct mailimf_address_list *cc = (myFields->fld_cc != NULL) ? (myFields->fld_cc->cc_addr_list) : NULL;
// struct mailimf_address_list *bcc = (myFields->fld_bcc != NULL) ? (myFields->fld_bcc->bcc_addr_list) : NULL;
clist *inReplyTo = (myFields->fld_in_reply_to != NULL) ? (myFields->fld_in_reply_to->mid_list) : NULL;
clist *references = (myFields->fld_references != NULL) ? (myFields->fld_references->mid_list) : NULL;
char *subject = (myFields->fld_subject != NULL) ? (myFields->fld_subject->sbj_value) : NULL;
//TODO uh oh, when this get freed it frees stuff in the CTCoreMessage
//TODO Need to make sure that fields gets freed somewhere
// fields = mailimf_fields_new_with_data(from, sender, replyTo, to, cc, bcc, inReplyTo, references, subject);
fields = mailimf_fields_new_with_data(from, sender, replyTo, to, cc, NULL, inReplyTo, references, subject);
[(CTMIME_MessagePart *)msgPart setIMFFields:fields];
}
return [myParsedMIME render];
}
Looks like the bug is with the framework itself, as the framework doesn't show anything that says the Bcc Address will be hidden
It is just showing that messages can be setted to bcc, cc and to.
I have digged the framework for 2 feet, but found nothing regarding the Bcc showing that it will be hidden at the receiving end...

Core Data optimization

I have a large list of Users in an NSDictionary that has a structure like this:
97 = {
birthday = "";
gender = Unspecified;
image = {
status = Prepared;
type = Image;
};
"name_display" = "Facebook User";
"name_first" = Facebook;
"name_last" = User;
type = Contact;
"user_id" = 97;
};
98 = {
birthday = "";
gender = Unspecified;
image = {
status = Prepared;
type = Image;
};
"name_display" = "Facebook User";
"name_first" = Facebook;
"name_last" = User;
type = Contact;
"user_id" = 98
}
I want to input this data into Core Data. First I must check if the user already exists in core data. If so, update that user. Otherwise create a new user. The way I am doing it works, but it is extremely slow. Here's my code:
NSDictionary *users = [responseData objectForKey:#"users"];
if (users) {
for (id userKey in [users allKeys]) {
NSDictionary *contactDictionary = [users objectForKey:userKey];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"userID == %#", userKey];
NSUInteger count = [CoreDataHelper countForEntity:#"Contact" withPredicate:predicate andContext:[FSAppDelegate managedObjectContext]];
if (count > 0) {
NSMutableArray *existingContactArray = [CoreDataHelper searchObjectsForEntity:#"Contact" withPredicate:predicate andSortKey:nil andSortAscending:NO andContext:[FSAppDelegate managedObjectContext]];
Contact *existingContact = [existingContactArray objectAtIndex:0];
[CoreDataHelper updateContactWithDictionary:contactDictionary forContactObject:existingContact];
}
else {
Contact *newContact = (Contact*)[NSEntityDescription insertNewObjectForEntityForName:#"Contact" inManagedObjectContext:[FSAppDelegate managedObjectContext]];
[CoreDataHelper updateContactWithDictionary:contactDictionary forContactObject:newContact];
}
}
NSError *error;
if (![[FSAppDelegate managedObjectContext] save:&error]) {
// Handle the error.
NSLog(#"error saving to db - fsrequest class.");
}
}
And here is my method to update the contact
+(BOOL)updateContactWithDictionary:(NSDictionary*)changedContact forContactObject:(Contact*)contact {
NSString *bday = [changedContact valueForKey:#"birthday"];
NSString *gender = [changedContact valueForKey:#"gender"];
NSString *nameDisplay = [changedContact valueForKey:#"name_display"];
NSString *nameFirst = [changedContact valueForKey:#"name_first"];
NSString *nameLast = [changedContact valueForKey:#"name_last"];
NSString *type = [changedContact valueForKey:#"type"];
NSString *userID = [NSString stringWithFormat:#"%#",[changedContact valueForKey:#"user_id"]];
NSString *imageStatus = [[changedContact objectForKey:#"image"]objectForKey:#"status"];
NSString *imageType = [[changedContact objectForKey:#"image"]objectForKey:#"type"];
NSString *imageURL = [[changedContact objectForKey:#"image"]objectForKey:#"url"];
NSString *imageThumb = [[changedContact objectForKey:#"image"]objectForKey:#"url_thumb"];
NSString *locationName = [[changedContact objectForKey:#"location"]objectForKey:#"name"];
[contact setBirthday:bday];
[contact setGender:gender];
[contact setNameDisplay:nameDisplay];
[contact setNameFirst:nameFirst];
[contact setNameLast:nameLast];
[contact setType:type];
[contact setUserID:userID];
[contact setImageStatus:imageStatus];
[contact setImageType:imageType];
if (imageURL && !((NSNull *)imageURL == [NSNull null])) {
[contact setImageURL:imageURL];
}
if (imageThumb && !((NSNull *)imageThumb == [NSNull null])) {
[contact setImageThumbURL:imageThumb];
}
if (locationName && !((NSNull *)locationName == [NSNull null])) {
[contact setLocationName:locationName];
}
return YES;
}
Can someone give me an example of how I would do this in a much faster way? Some people have mentioned some ideas, but I need to see it to understand. Thanks!
First of all I'd move save: outside the loop. Replace:
// save core data
NSError *error;
if (![[FSAppDelegate managedObjectContext] save:&error]) {
// Handle the error.
NSLog(#"error saving to db - fsrequest class.");
}
}
}
with
}
// save core data
NSError *error;
if (![[FSAppDelegate managedObjectContext] save:&error]) {
// Handle the error.
NSLog(#"error saving to db - fsrequest class.");
}
}
Also, do you have some default values for imageURL, imageThumb and locationName defined in Core Data model? If no, why do you check for nulls (twice)?
Bonus:
It may be a good idea to eliminate countForEntity:withPredicate:andContext: call, like this:
NSMutableArray *existingContactArray = [CoreDataHelper searchObjectsForEntity:#"Contact" withPredicate:predicate andSortKey:nil andSortAscending:NO andContext:[FSAppDelegate managedObjectContext]];
if ([existingContactArray count] > 0)
{
Contact *existingContact = [existingContactArray objectAtIndex:0];
[CoreDataHelper updateContactWithDictionary:contactDictionary forContactObject:existingContact];
}
You need to understand that a fetch request is expensive (it needs to run SQL and do I/O). I'm not sure where your CoreDataHelper comes from, but it will do some sort of NSFetchRequest which is expensive. You can construct a single NSFetchRequest which will tell you which objects already exists. That will reduce the cost from O(N) to O(1).
[request setPredicate:[NSPredicate predicateWithFormat:#"userID IN %#", allKeys]];
And, as noted above, move the saves out of the loop. But if you're updating adding a many objects, you might want to save every now and then.

Why does Keychain Services return the wrong keychain content?

I've been trying to use persistent keychain references in an iPhone application. I found that if I created two different keychain items, I would get a different persistent reference each time (they look like 'genp.......1', 'genp.......2', …). However, attempts to look up the items by persistent reference always returned the content of the first item. Why should this be? I confirmed that my keychain-saving code was definitely creating new items in each case (rather than updating existing items), and was not getting any errors. And as I say, Keychain Services is giving a different persistent reference for each item.
I've managed to solve my immediate problem by searching for keychain items by attribute rather than persistent references, but it would be easier to use persistent references so I'd appreciate solving this problem.
Here's my code:
- (NSString *)keychainItemWithName: (NSString *)name {
NSString *path = [GLApplicationSupportFolder()
stringByAppendingPathComponent: name];
NSData *persistentRef = [NSData dataWithContentsOfFile: path];
if (!persistentRef) {
NSLog(#"no persistent reference for name: %#", name);
return nil;
}
NSArray *refs = [NSArray arrayWithObject: persistentRef];
//get the data
CFMutableDictionaryRef params = CFDictionaryCreateMutable(NULL,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFDictionaryAddValue(params, kSecMatchItemList, refs);
CFDictionaryAddValue(params, kSecClass, kSecClassGenericPassword);
CFDictionaryAddValue(params, kSecReturnData, kCFBooleanTrue);
CFDataRef item = NULL;
OSStatus result = SecItemCopyMatching(params, (CFTypeRef *)&item);
CFRelease(params);
if (result != errSecSuccess) {
NSLog(#"error %d retrieving keychain reference for name: %#", result, name);
return nil;
}
NSString *token = [[NSString alloc] initWithData: (NSData *)item
encoding: NSUTF8StringEncoding];
CFRelease(item);
return [token autorelease];
}
- (void)setKeychainItem: (NSString *)newToken forName: (NSString *)name {
NSData *tokenData = [newToken dataUsingEncoding: NSUTF8StringEncoding];
//firstly, find out whether the item already exists
NSDictionary *searchAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
name, kSecAttrAccount,
kCFBooleanTrue, kSecReturnAttributes,
nil];
NSDictionary *foundAttrs = nil;
OSStatus searchResult = SecItemCopyMatching((CFDictionaryRef)searchAttributes,
(CFTypeRef *)&foundAttrs);
if (noErr == searchResult) {
NSMutableDictionary *toStore = [foundAttrs mutableCopy];
[toStore setObject: tokenData forKey: (id)kSecValueData];
OSStatus result = SecItemUpdate((CFDictionaryRef)foundAttrs,
(CFDictionaryRef)toStore);
if (result != errSecSuccess) {
NSLog(#"error %d updating keychain", result);
}
[toStore release];
return;
}
//need to create the item.
CFMutableDictionaryRef params = CFDictionaryCreateMutable(NULL,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFDictionaryAddValue(params, kSecClass, kSecClassGenericPassword);
CFDictionaryAddValue(params, kSecAttrAccount, name);
CFDictionaryAddValue(params, kSecReturnPersistentRef, kCFBooleanTrue);
CFDictionaryAddValue(params, kSecValueData, tokenData);
NSData *persistentRef = nil;
OSStatus result = SecItemAdd(params, (CFTypeRef *)&persistentRef);
CFRelease(params);
if (result != errSecSuccess) {
NSLog(#"error %d from keychain services", result);
return;
}
NSString *path = [GLApplicationSupportFolder()
stringByAppendingPathComponent: name];
[persistentRef writeToFile: path atomically: NO];
[persistentRef release];
}
Turns out that using the kSecMatchItemList doesn't appear to work at all.
I did mine like this:
NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassGenericPassword, kSecClass,
persistentRef, (id)kSecValuePersistentRef,
(id)kCFBooleanTrue, kSecReturnAttributes,
(id)kCFBooleanTrue, kSecReturnData,
nil];
NSDictionary *result = nil;
OSStatus status = SecItemCopyMatching((CFDictionaryRef)query,
(CFTypeRef*)&result);
which returned the attributes and data for the persistent reference. The documentation in the header about converting a "persistent reference" into a "standard reference" makes no sense at all. Hope this helps.