Ошибка в добавлении фотографии из моей библиотеки?
Код, который я разместил ниже, имеет две функции; первая - сделать фотографию (которая работает нормально), а вторая - выбрать изображение из библиотеки (которая не работает). Функции не вызываются должным образом. Пожалуйста, проверьте мой код и дайте мне знать, что не так.
Заранее спасибо.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
static NSDateFormatter *dateFormatter = nil;
NSString *stringDate = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EE, d LLLL yyyy"];
stringDate = [dateFormatter stringFromDate:[NSDate date]];
}
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// storing to camera roll
UIImageWriteToSavedPhotosAlbum(image,self,@selector(image:finishedSavingWithError:contextInfo:),nil);
CGSize newSize=CGSizeMake(320, 436);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
xapp.profileImage=newImage;
[[NSNotificationCenter defaultCenter]postNotificationName:@"addImage" object:nil];
}
// Commit the change.
[self dismissModalViewControllerAnimated:YES];
}
-(void)image:(UIImage *)image finishedSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: @"Save failed"
message: @"Failed to save image"
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
2 ответа
Привет, я просто поместил код полного захвата изображения из камеры библиотеки фотографий, просто проверьте его и попробуйте внести в ваш проект:-
-(IBAction)actionImage:(id)sender
{
UIActionSheet *option =[[UIActionSheet alloc]initWithTitle:@"Select" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Select Photo",@"Take Photo",nil];
option.actionSheetStyle =UIActionSheetStyleDefault;
[option showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (actionSheet.tag==2)
{
[self.navigationController popViewControllerAnimated:YES];
}
else
{
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if(buttonIndex ==0)
{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
{
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
}
}
else if(buttonIndex ==1)
{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:picker animated:YES];
}
}
}
}
#pragma mark - imagePickerController Delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissModalViewControllerAnimated:YES];
imgUserImage.image = [info valueForKey:@"UIImagePickerControllerOriginalImage"];
return;
}
ПРИМЕЧАНИЕ:- НЕ забывайте включать связанные рамки или делегировать. Надеюсь, что с его помощью вам не понадобится дополнительное кодирование для этого материала, который вы просто делаете с помощью вышеуказанного метода:)
В вашем коде нужно внести много изменений... Вот код для выбора изображения из библиотеки... Я думаю, что лучше дать вам код, а не исправлять ошибки в вашем... так вот код... наслаждайтесь...
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = info[UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = info[UIImagePickerControllerOriginalImage];
_imageView.image = image;
if (_newMedia)
UIImageWriteToSavedPhotosAlbum(image,
self,
@selector(image:finishedSavingWithError:contextInfo:),
nil);
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
// Code here to support video if enabled
}
}
-(void)image:(UIImage *)image
finishedSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo
{
if (error) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: @"Save failed"
message: @"Failed to save image"
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}