1

ABPeoplePickerNavigationController を使用して、iPhone の連絡先をアプリにインポートします。最近、サムネイル画像を保存するだけでなく、画像全体も保存することにしました。iPad を使用していて、トリミングの異なる大きな画像が必要になる可能性がある場合は、これが最適な方法だと思います。ただし、インポート後に新しい連絡先を保存する場合、写真のサイズによっては保存に時間がかかります。写真がなく、すぐに保存されるので、写真のサイズと、その写真で何をしているかに関係していることはわかっています。誰かが私が間違っていることを指摘できる場合に備えて、関連するコードを以下に示します...

    - (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)contact {

    NSLog(@"%s", __FUNCTION__);
    self.selectedThumbnailImage = nil;
    self.selectedImage = nil;   

    if(ABPersonHasImageData(contact)){

        self.selectedThumbnailImage = nil;
        NSData *imgData = (NSData *)ABPersonCopyImageData(contact); 
        UIImage *pickedImage = [UIImage imageWithData:imgData];
        [imgData release];

        self.selectedImage = pickedImage;

        CGSize imageSize = pickedImage.size;
        CGSize targetSize = CGSizeMake(110.0,120.0);
        CGFloat width = imageSize.width;
        CGFloat height = imageSize.height;
        CGFloat targetWidth = targetSize.width;
        CGFloat targetHeight = targetSize.height;
        CGFloat scaleFactor = 0.0;
        CGFloat scaledWidth = targetWidth;
        CGFloat scaledHeight = targetHeight;
        CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

        if (CGSizeEqualToSize(imageSize, targetSize) == NO) 
        {
            CGFloat widthFactor = targetWidth / width;
            CGFloat heightFactor = targetHeight / height;

            if (widthFactor > heightFactor) 
                scaleFactor = widthFactor; // scale to fit height
            else
                scaleFactor = heightFactor; // scale to fit width
            scaledWidth  = width * scaleFactor;
            scaledHeight = height * scaleFactor;

            // center the image
            if (widthFactor > heightFactor)
            {
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
            }
            else 
                if (widthFactor < heightFactor)
                {
                    thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
                }
        }       

        UIGraphicsBeginImageContext(targetSize);

        CGRect thumbnailRect = CGRectZero;
        thumbnailRect.origin = thumbnailPoint;
        thumbnailRect.size.width  = scaledWidth;
        thumbnailRect.size.height = scaledHeight;

        [pickedImage drawInRect:thumbnailRect];

        self.selectedThumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
        [[NSNotificationCenter defaultCenter] postNotificationName:@"personChanged" object:nil]; 

        UIGraphicsEndImageContext();
    }

    self.nameFirstString = (NSString *)ABRecordCopyValue(contact, kABPersonFirstNameProperty);
    self.nameLastString = (NSString *)ABRecordCopyValue(contact, kABPersonLastNameProperty);
    [nameFirstTextField setText:nameFirstString];
    [nameLastTextField setText:nameLastString];

    self.person.birthday = (NSDate *)ABRecordCopyValue(contact, kABPersonBirthdayProperty); 

    [self updateRightBarButtonItemState];
    [self dismissModalViewControllerAnimated:YES];

    return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{

    NSLog(@"%s", __FUNCTION__);
    return NO;
}

- (void)saveImage {

    // Delete any existing image.
    NSManagedObjectContext *context = [[UIApplication sharedDelegate] managedObjectContext];
    Image *oldImage = person.image;
    if (oldImage != nil) {
        [context deleteObject:(NSManagedObject*)oldImage];
    }

    // Create an image object for the new image.
    UIImage *newImage = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:context];
    [newImage setValue:selectedImage forKey:@"image"];
    [self.person setValue:newImage forKey:@"image"];
}
- (IBAction)save:(id)sender {

    NSLog(@"%s", __FUNCTION__);

    [self.person setValue:selectedThumbnailImage forKey:@"thumbnailImage"];
    [self saveImage];

    self.person.nameFirst = nameFirstString;
    self.person.nameLast = nameLastString;

    NSError *error;
    NSManagedObjectContext *context = [[UIApplication sharedDelegate] managedObjectContext];
    if (![context save:&error]) {
        NSLog(@"AddPersonViewController - addViewControllerDidFinishWithSave - Person MOC save error %@, %@", error, [error userInfo]);
        exit(-1);  // Fail
    }

    [self.delegate addPersonViewController:self didFinishWithSave:YES didEditPerson:person];
}

編集: saveImage コードを次のように変更したところ、「異なるコンテキスト内のオブジェクト間に関係 'person' を確立しようとする不正な試み」というエラーが表示されました。

- (void)saveImage {

// Delete any existing image.
//NSManagedObjectContext *context = [[UIApplication sharedDelegate] managedObjectContext];

NSLog(@"%s", __FUNCTION__);

NSManagedObjectContext *savingPhotoContext = [[NSManagedObjectContext alloc] init];
self.savingPhotoMOC = savingPhotoContext;                                                           
[savingPhotoMOC setPersistentStoreCoordinator:[[[UIApplication sharedDelegate] managedObjectContext] persistentStoreCoordinator]];
[savingPhotoContext release];       

Image *oldImage = person.image;
if (oldImage != nil) {
    [savingPhotoMOC deleteObject:(NSManagedObject*)oldImage];
}

// Create an image object for the new image.
UIImage *newImage = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:savingPhotoMOC];
[newImage setValue:selectedImage forKey:@"image"];
[newImage setValue:self.person forKey:@"person"];
//[self.person setValue:newImage forKey:@"image"];

NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
[dnc addObserver:self selector:@selector(addControllerContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:savingPhotoMOC];

NSError *error;
if (![savingPhotoMOC save:&error]) {
    NSLog(@"Occasion View Controller - addViewControllerDidFinishWithSave - Adding MOC save error %@, %@", error, [error userInfo]);
    exit(-1);  // Fail
}
[dnc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:savingPhotoMOC];
self.savingPhotoMOC = nil;

}- (void)addControllerContextDidSave:(NSNotification*)saveNotification {

NSLog(@"%s", __FUNCTION__);
NSManagedObjectContext *context = [[UIApplication sharedDelegate] managedObjectContext];
[context mergeChangesFromContextDidSaveNotification:saveNotification];  

}

4

1 に答える 1

1

時間がかかる場合は、これをバックグラウンドで実行し、デリゲート コールバックまたは nsnotification を使用して、保存が完了したときにそれを使用している可能性のある他の関数に通知する必要があります。GCD または nsoperationqueue を使用できます... gcd については、'fiery robot's blog をご覧ください。彼はコピペ用のコードだけでなく物事を説明してくれるので気に入っています。

于 2011-10-10T11:40:07.873 に答える