UIImagePickerControllerMediaURL always nil? - ios

I'm trying to pick a video from PhotoAlbum. I'm using the UIImagePickerController but every time after i chose the video UIImagePickerControllerMediaURL is returning nil.
What I am missing?
Thanks.
- (IBAction)galerry:(id)sender {
self.imagePickerController = [[UIImagePickerController alloc] init];
[self.imagePickerController setDelegate:self];
self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
self.imagePickerController.mediaTypes =#[(NSString *)kUTTypeMovie,(NSString *)kUTTypeVideo];
[self.imagePickerController setVideoMaximumDuration:20];
self.imagePickerController.allowsEditing = YES;
[self presentViewController:self.imagePickerController animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSURL *videoURL= [info objectForKey:UIImagePickerControllerMediaURL];
NSURL *videoUrl=(NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];
NSString *moviePath = [videoUrl path];
NSURL *imagePickerURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSURL *videoURL2= [info valueForKey:UIImagePickerControllerMediaMetadata];
// picker.videoQuality=UIImagePickerControllerQualityTypeMedium;
[picker dismissViewControllerAnimated:YES completion:^{
Edition *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"EditionVC"];
vc.videoUrl=videoURL;
[self presentViewController:vc animated:YES completion:nil];
}];
}
All variables returning nil (videoURL,videoUrl,imagePickerURL,videoURL2).
What is wrong here?
EDIT:
This is my info dictionary:
po info
{
UIImagePickerControllerMediaType = "public.movie";
UIImagePickerControllerReferenceURL = "assets-library://asset/asset.MOV?id=87B8D3F5-DE9C-4F06-A88B-5116055A618A&ext=MOV";
}

#import <MobileCoreServices/UTCoreTypes.h>
- (void)getVideo {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = #[ (NSString *) kUTTypeMovie ];
[self presentViewController:imagePicker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = info[ UIImagePickerControllerMediaType ];
if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
NSURL *videoUrl=(NSURL*) info[ UIImagePickerControllerMediaURL ];
NSString *moviePath = [videoUrl path];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath)) {
UISaveVideoAtPathToSavedPhotosAlbum (moviePath, nil, nil, nil);
}
}
[self dismissViewControllerAnimated:YES completion:nil];
}

Related

UIButton's IBAction only works the first time it is tapped

Using Apple's template "Tabbed Bar Banner" I found that the button in one of the views only works the first times I pressed it.
If the iPhone is connected to Xcode to run the app, it works great. Once I have detached the cable, the button stops working.
- (IBAction)sendData:(id)sender {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.allowsEditing = YES;
[self presentViewController:imagePicker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:^{
[self openEmail];
}];
}
-(IBAction) openEmail {
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
[mailComposer setMailComposeDelegate:self];
if ([MFMailComposeViewController canSendMail]) {
[mailComposer setToRecipients:[NSArray arrayWithObjects:#"*******", nil]];
[mailComposer setSubject:self.nameTextField.text];
NSLog(#"self.nameTextField.text = %#", *********);
[mailComposer setMessageBody:#"******r" isHTML:NO];
[mailComposer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Answer" ofType:#"plist"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[mailComposer addAttachmentData:myData mimeType:#"application/xml" fileName:#"Answer.plist"];
NSData *imageData = UIImageJPEGRepresentation(selectedImage, 0.5);
[mailComposer addAttachmentData:imageData mimeType:#"image/jpg" fileName:[NSString stringWithFormat:#"%#.jpg",*********]];
[self composeCSV];
NSString *fileName = [file lastPathComponent];
[mailComposer addAttachmentData:[NSData dataWithContentsOfFile:file] mimeType:#"text/csv" fileName:fileName];
[self presentViewController:mailComposer animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)composeCSV{
NSMutableString *mainString = [[ NSMutableString alloc]initWithString:#"++;++;++;++;...\n"];
[mainString appendFormat:#"%#;\n",...];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
file = [NSString stringWithFormat:#"%#/%#.csv",documentsDirectoryPath,******];
NSError *csVerror= NULL;
BOOL written = [mainString writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:&csVerror];
if (!written) {
NSLog( #"Writing failed, error = %#",csVerror);
}else {
NSLog(#"Data saved! File path = %#",file);
}
}

Save a picture after the application is closed

There is a simple application, on the storyboard added UIImageView and button
Button opens the photo gallery, and I choose an image and eventually it appears on the UIimaeView
But when I kill the application snapshot is not saved What to do?
this my code :
-(IBAction)takePic:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
self.image.image=[info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:nil];
}
ok. try this:
#import "ViewController.h"
#import AssetsLibrary;
#interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
#property (weak, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) UIImagePickerController *picker;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSURL *selectedImageURL = [NSURL URLWithString:[userDefaults objectForKey:#"selectedImageURL"]];
if (selectedImageURL) {
[self getImageFromAssetsAtURL:selectedImageURL completion:^(UIImage *image, NSError *error) {
if (!error && image) {
self.imageView.image = image;
}
}];
}
}
- (IBAction)pickImage:(UIButton *)sender {
[self presentViewController:self.picker animated:YES completion:nil];
}
- (UIImagePickerController *)picker {
if (!_picker) {
_picker = [UIImagePickerController new];
_picker.delegate = self;
_picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
}
return _picker;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
NSURL *selectedImageURL = info[UIImagePickerControllerReferenceURL];
// set image
self.imageView.image = selectedImage;
// save image url
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:selectedImageURL.absoluteString forKey:#"selectedImageURL"];
[userDefaults synchronize];
// dismiss
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)getImageFromAssetsAtURL:(NSURL *)imageURL completion:(void (^)(UIImage *, NSError *))completion {
ALAssetsLibrary *library = [ALAssetsLibrary new];
[library assetForURL:imageURL resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];
completion(image, nil);
} failureBlock:^(NSError *error) {
completion(nil, error);
}];
}
#end
since the AssetsLibrary is deprecated as of iOS 9.0 you could and should use the Photos framework instead. you have to import it...
#import Photos;
and change the getImageFromAssetsAtURL... method to the following:
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[imageURL] options:nil];
if (result.count == 1) {
PHAsset *asset = result.firstObject;
[[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
UIImage *selectedImage = [UIImage imageWithData:imageData];
completion(selectedImage, nil);
}];
} else {
completion(nil, nil);
}
Finally I used this code.
-(void)viewDidLoad {
[super viewDidLoad];
[self loadDefaultImage];
}
-void)viewDidAppear:(BOOL)animated
{
[self loadDefaultImage];
}
- (IBAction)TakePic:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
-(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];
//append filename to document directory url
NSURL *urlSave = [[self getDocumentsPathURL] URLByAppendingPathComponent:#"imagee"];
//do something to previously taken image (in this case: delete it)
if ([[NSFileManager defaultManager] fileExistsAtPath:urlSave.path]) {
[[NSFileManager defaultManager] removeItemAtPath:urlSave.path error:nil];
}
//save image to document directory
[UIImagePNGRepresentation(image) writeToFile:urlSave.path atomically:YES];
//optional: save image to photo library
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}
-(NSURL *)getDocumentsPathURL
{
//document directory of app
return [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
}
-(void)loadDefaultImage
{
NSURL *urlImage = [[self getDocumentsPathURL] URLByAppendingPathComponent:#"imagee"];
if ([[NSFileManager defaultManager] fileExistsAtPath:urlImage.path]) {
NSData *dataFile = [[NSFileManager defaultManager] contentsAtPath:urlImage.path];
UIImage *image = [UIImage imageWithData:dataFile];
[_imageView setImage:image];
}
else {
NSLog(#"Image not found");
}
}

copy gallery image to project files Objective-C

I am new in Objective-C and I want choose one image from a Gallery and I want get the name and the extension and copy that image to my project folder.
Use UIimagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
if ([mediaTypeStr isEqualToString:#"photo"])
{
if ([info objectForKey:UIImagePickerControllerOriginalImage])
{
// images = [NSMutableArray arrayWithCapacity:[info count]];
_images = [[NSMutableArray alloc]init];
UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];;
img =[self scaleAndRotateImage:img];
[_images addObject:img];
// Save Photo to library only if it wasnt already saved i.e. its just been taken
[self.alAsstlibrary saveImage:img toAlbum:#"FOlder name" completion:^(NSURL *assetURL, NSError *error)
{
if (error!=nil)
{
//NSLog(#"Big error: %#", [error description]);
}
} failure:nil];
}
else
{
//NSLog(#"UIImagePickerControllerReferenceURL = %#", info);
}
}
[picker dismissViewControllerAnimated:YES completion:Nil];
}
write these in viewdidload or on the buttons click event as per your need..
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = NO;//by writing YES here you can edit image also..
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
imgview=[[UIImageView alloc]initWithFrame:CGRectMake(x+y, y, width, height)];
[imgview setTag:i];
imgview.contentMode = UIViewContentModeScaleAspectFill;
[imgview setClipsToBounds:YES];
[self.view addSubview:imgview];
write these in your .m file..
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//if you write picker.allowsEditing = YES; than write info[UIImagePickerControllerEditedImage] in BELOW line....
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
imgview.image = chosenImage;//set selected image in your imageview
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:NULL];
}
i hope it helps..
To achieve this follow these steps.
Get the image
- (void) getPicture:(id)sender
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = (sender == myPic) ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentModalViewController:picker animated:YES];
[picker release];
}
You will get the image in imagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage (UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self save:image];
[picker dismissModalViewControllerAnimated:YES];
}
Save image in documents
-(void)save:(UIImage*)image
{
NSData *pngData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
}
Get document path
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return [documentsPath stringByAppendingPathComponent:name];
}
Get the Image
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:pngData];

SDWebImage ,setImageWithUrl can't show the image on the imageView

- (void)xuanquButtonClicked:(JohnButtonLong*)button
{
_picker = [[UIImagePickerController alloc] init];
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
JLActionManager * manager = [JLActionManager sharedInstance];
[manager showAndHideHUDWithTitle:nil detailText:#"亲,您的相册无法打开" inView:self.view];
return;
}
_picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
_picker.allowsEditing = YES;
_picker.delegate = self;
[self presentViewController:_picker animated:YES completion:^{
}];
}
#pragma mark - UIIMagePickerController delegate Methods
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:^{
}];
// 如果没有选取 使用默认头像
_strHeadPic = #"";
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:^{
}];
// 选取了某个头像
UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
_img_touxiang.image = image;
//压缩图像
image = [self OriginImage:image scaleToSize:CGSizeMake(160, 160)];
NSData * img_data = UIImageJPEGRepresentation(image, 0.5);
//进行base64编码
NSData * data = [GTMBase64 encodeData:img_data];
_strHeadPic = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
// 压缩成指定大小
-(UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size{
UIGraphicsBeginImageContext(size);
// 绘制改变大小的图片
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
// 从当前context中创建一个改变大小后的图片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();// 是当前的context出对战
// 返回新的改变大小后的图片
return scaledImage;
}
UnitMyInfo * myInfo = GetMyInfo;
[_img_touxiang setImageWithURL:[NSURL URLWithString:BaseImgURL(myInfo.umi_URL)] placeholderImage:[UIImage imageNamed:#"default_headImg.jpg"]];
// First You have to get Url from Image then set url On SDWebImages.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editingInfo
{
[picker dismissModalViewControllerAnimated:YES];
NSURL *imagePath = [editingInfo objectForKey:#"UIImagePickerControllerReferenceURL"];
NSString *imageName = [imagePath lastPathComponent];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"localFilePath.%#",localFilePath);
}
//Set Image On SDWebView.
[imageView setImageWithURL:[NSURL URLWithString:localFilePath] placeholderImage:[UIImage imageNamed:#"default_headImg.jpg"]];

Picker is not returning any image if allowsEditing=NO

As the title suggests, if I set
imagePickerController.allowsEditing = YES;
to
imagePickerController.allowsEditing = NO
I get no image returned? I have searched SO and can not find a definitive answer
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.delegate = self;
imagePicker.allowsEditing = NO;
[self.editController presentModalViewController:imagePicker animated:YES];
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
DebugLog(#"info dict: %#", info);
[picker dismissModalViewControllerAnimated:YES];
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
self.schemeLogo.backgroundColor = [UIColor whiteColor];
self.schemeLogo.image = image;
NSData *imageData1 = UIImagePNGRepresentation(image);
NSString *path1 = [ICUtils pathForDocument:#"schemeLogo.png"];
[imageData1 writeToFile:path1 atomically:NO];
}
Fixed, needed
[info objectForKey:UIImagePickerControllerOriginalImage];

Resources