I'm trying to do a small class to manage Sqlite. I want to store the data retrieved from the DB into an array of objects but get app crashed (BAD_ACCESS)
My code:
- (ArrayList *) execNonQuery: (char *) query {
#try {
sqlite3_stmt *sqlStat;
ArrayList *dataList;
if(sqlite3_prepare_v2(self->dbHandle, query, -1, &sqlStat, NULL) == SQLITE_OK) {
dataList = [[ArrayList alloc] init];
while (sqlite3_step(sqlStat) == SQLITE_ROW) {
NSMutableArray *list = [[NSMutableArray alloc] init];
for (int i = 0; i < sqlite3_column_count(sqlStat); i++) {
// CRASH
id data = (__bridge id)(sqlite3_column_value(sqlStat, i));
[list addObject: data];
}
[dataList addList:list];
}
}
sqlite3_finalize(sqlStat);
return dataList;
}
#catch (NSException *exception) {
NSLog(#"Excepción capturada: %#", [exception reason]);
return NULL;
}
}
I think the problem is when i try to do:
id data = (__bridge id)(sqlite3_column_value(sqlStat, i));
Note: The ArrayList Class is just NSMutableArray of NSMutableArray
Im noob in objective c, just learning... and sorry for spelling errors.
Best regards.
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
}];
I'm trying to copy contacts between my Local contact source and the iCloud contact source and I'm not seeing any results. This code executes without error and seems like it should work, but I don't see the newly created contacts afterward. Anyone see any issues with it?
ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef abSourceSource = ABAddressBookGetSourceWithRecordID(addressBook, kABSourceTypeLocal);
ABRecordRef abDestinationSource = ABAddressBookGetSourceWithRecordID(addressBook, kABSourceTypeCardDAV);
CFArrayRef sourceContacts = ABAddressBookCopyArrayOfAllPeopleInSource(addressBook, abSourceSource);
CFArrayRef destinationContacts = ABAddressBookCopyArrayOfAllPeopleInSource(addressBook, abDestinationSource);
ABPersonCreatePeopleInSourceWithVCardRepresentation(abDestinationSource, ABPersonCreateVCardRepresentationWithPeople(sourceContacts));
ABPersonCreatePeopleInSourceWithVCardRepresentation(abSourceSource, ABPersonCreateVCardRepresentationWithPeople(destinationContacts)));
ABAddressBookSave(addressBook, NULL);
There is a more fundamental problem - you are not calling ABAddressBookGetSourceWithRecordID properly. The 2nd parameter it takes is an int that specifies the record id of a particular source in your address book. You are passing it a constant that describes the type of a particular source.
The constant you are passing, kABSourceTypeCardDav is always 4. However, the record id of the iCloud source in a user's address book can be something very different.
What you need to do is enumerate all the sources and test their types, like so:
NSArray *allSources = (NSArray*)ABAddressBookCopyArrayOfAllSources(addressBook);
for (int i = 0; i < allSources.count; i++) {
ABRecordRef src = [allSources objectAtIndex:i];
NSNumber *stObj = (NSNumber*)ABRecordCopyValue(src, kABSourceTypeProperty);
ABSourceType st = (ABSourceType)[stObj intValue];
if (st == kABSourceTypeCardDAV) {
int recordID = ABRecordGetRecordID(src);
break;
}
}
Then you could use recordID as the argument to the first function
I think you forgot to add the records with ABAddressBookAddRecord. Here is my working example:
ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef abSource = ABAddressBookGetSourceWithRecordID(addressBook, kABSourceTypeLocal);
NSURL *theURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"some.vcf"];
NSData *vCardData = [NSData dataWithContentsOfURL:theURL];
NSLog(#"data %#", vCardData);
NSArray *createdPeople = (__bridge_transfer NSArray*)ABPersonCreatePeopleInSourceWithVCardRepresentation(abSource, (__bridge CFDataRef)vCardData);
NSLog(#"createdPeople %#", createdPeople);
CFErrorRef error = NULL;
bool ok;
for (id person in createdPeople) {
error = NULL;
ok = ABAddressBookAddRecord(addressBook, (__bridge ABRecordRef)person, &error);
if (!ok) {
NSLog(#"add err %#", error);
break;
}
}
if (ok) {
error = NULL;
BOOL isSaved = ABAddressBookSave(addressBook, &error);
if (isSaved) {
NSLog(#"saved..");
}
if (error != NULL) {
NSLog(#"ABAddressBookSave %#", error);
}
}
CFRelease(addressBook);
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
I want to delete a contact from the address book in iPhone how can we do that ?
Thanks
ABAddressBookRemoveRecord
http://developer.apple.com/iphone/library/documentation/AddressBook/Reference/ABAddressBookRef_iPhoneOS/Reference/reference.html#//apple_ref/c/func/ABAddressBookRemoveRecord
Here is a sample code to do the same:
- (void)delAllContacts {
ABAddressBookRef addressBook = CFBridgingRetain((__bridge id)(ABAddressBookCreateWithOptions(NULL, NULL)));
int count = ABAddressBookGetPersonCount(addressBook);
if(count==0 && addressBook!=NULL) { //If there are no contacts, don't delete
CFRelease(addressBook);
return;
}
//Get all contacts and store it in a CFArrayRef
CFArrayRef theArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(CFIndex i=0;i<count;i++) {
ABRecordRef person = CFArrayGetValueAtIndex(theArray, i); //Get the ABRecord
BOOL result = ABAddressBookRemoveRecord (addressBook,person,NULL); //remove it
if(result==YES) { //if successful removal
BOOL save = ABAddressBookSave(addressBook, NULL); //save address book state
if(save==YES && person!=NULL) {
CFRelease(person);
} else {
NSLog(#"Couldn't save, breaking out");
break;
}
} else {
NSLog(#"Couldn't delete, breaking out");
break;
}
}
if(addressBook!=NULL) {
CFRelease(addressBook);
}
}
+(BOOL)removedRecordFromAddressBookWithFirstValue:(NSString *)fullName{
BOOL recordRemoved=NO;
CFErrorRef err;
ABAddressBookRef addressBook=
ABAddressBookCreateWithOptions(NULL,&err);
CFArrayRef people=ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople=ABAddressBookGetPersonCount(addressBook);
NSString *currRecordFullName=[[NSString alloc] init];
/*Invariant: No record with the name fullName has been
found so far.*/
for(int i=0;i<nPeople;i++){
ABRecordRef ref=CFArrayGetValueAtIndex(people,i);
CFErrorRef error=NULL;
currRecordFullName=nil;
currRecordFullName=[[NSString alloc] init];
currRecordFullName=
(__bridge NSString *)ABRecordCopyCompositeName(ref);
if([currRecordFullName isEqualToString:fullName]){
/*The record to be deleted has been found.*/
ABAddressBookRemoveRecord(addressBook,ref,&error);
ABAddressBookSave(addressBook,&error);
CFRelease(ref);
CFRelease(addressBook);
if(error!=NULL){
CFStringRef errorDesc=CFErrorCopyDescription(error);
NSLog(#"Failed to remove record: %#",errorDesc);
CFRelease(errorDesc);
}else{
NSLog(#"Record removed");
recordRemoved=YES;
}
break;
}else{;}
}
return recordRemoved;
}