Getting duration and creation date from video from ios library - ios

I'm trying to select/compress a video from the photo library but when I go to get the duration and creation date, they both are returning null (for duration this defaults to 0.0 sec). I'm not sure if I'm doing something wrong here.
- (void)imagePickerController:(UIImagePickerController *)uploadPick didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if (CFStringCompare (( CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo)
{
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
//Video Duration:
MPMoviePlayerController *mp = [[MPMoviePlayerController alloc]
initWithContentURL:videoURL];
VideoTime.text = [NSString stringWithFormat:#"Time: %.2f", mp.duration];
//Video Creation Date
NSDictionary *metadataDictionary = (NSDictionary *)[info valueForKey:UIImagePickerControllerMediaMetadata];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *stringDate = [dateFormatter stringFromDate:metadataDictionary.fileCreationDate];
[dateFormatter release];
VideoDateTaken.text = [NSString stringWithFormat:#"Date Taken: %#", stringDate];
}
}

According to the documentation, UIImagePickerControllerMediaMetadata is only valid for still images:
This key is valid only when using an image picker whose source type is
set to UIImagePickerControllerSourceTypeCamera, and applies only to
still images.
In order do get the metadata you want, use an ALAsset and the metadata method.

Related

get the location metadata of a video I choose in photoLibrary iOS objective-c

I am selecting a video from the photo library using UIImagePickerController. I have gotten the creation time and date of the video and I would like to get the location it was taken at. I know that the videos taken on the iphone have the location as part of their metadata but I don't know how to access it.
Here is the code I used for the dat and time.
else if (picker.sourceType ==UIImagePickerControllerSourceTypePhotoLibrary) {
NSURL * movieURL = [info valueForKey:UIImagePickerControllerMediaURL] ;
AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:movieURL options:nil];
PHAsset *theAsset = [info valueForKey:UIImagePickerControllerMediaURL] ;
PHAsset *someAsset = [info valueForKey:UIImagePickerControllerPHAsset];
NSLog(#"someAsset%#",someAsset.location);
self.currentLocation = someAsset.location;
NSLog(#"creationDate1:%#",theAsset);
NSLog(#"creationDate2:%#",anAsset.creationDate.value);
NSDate *creationDate =(NSDate *)anAsset.creationDate.value;
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMMM-dd-yyyy"];
dayString = [dateFormatter stringFromDate:creationDate];
NSDateFormatter *dateFormatter2=[[NSDateFormatter alloc] init];
[dateFormatter2 setDateFormat:#"hh:mm a"];
timeString = [dateFormatter2 stringFromDate:creationDate];
I have tried to find the location key but with no luck.
Can someone show me how to do this or point me to a good tutorial and how to accomplish this. I am using objective-c.
Thanks for any and all help.
So I finally figured this out. I added these lines of code
PHAsset *someAsset = [info valueForKey:UIImagePickerControllerPHAsset];
NSLog(#"someAsset%#",someAsset.location);
self.currentLocation = someAsset.location;
I will change my original post to reflect changes.

Is it possible to add own metadata in captured Images in Swift

I'm very new to Swift and Ios programming. I like to, as mentioned above, insert my own metadata to captured images before i save them to album.
I'm trying to get this done with this code. The saved image does not contain my own metadata, but its generated metadata. Can anybody please tell me what I'm doing wrong?
Or maybe isn't it possible to add own new metadata table to captured images?
Thanks a lot for your help
#IBAction func btnPressed(sender: UIButton) {
capturePicture()
}
func capturePicture(){
stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
session.addOutput(stillImageOutput)
if let connection = self.stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) {
self.stillImageOutput.captureStillImageAsynchronouslyFromConnection(connection) {
(imageDataSampleBuffer, error) -> Void in
if error == nil {
var asset = ALAssetsLibrary()
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
// The Metadata of the Image
var metadata:NSDictionary = CMCopyDictionaryOfAttachments(nil, imageDataSampleBuffer, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate)).takeUnretainedValue()
// My Metadata i want to add for testing purpose
var meta : NSDictionary = ["Ersteller": "Dennis","Datum" : "25.04.14","Ort" : "Köln" ]
asset.writeImageDataToSavedPhotosAlbum(imageData, metadata: meta as [NSObject : AnyObject], completionBlock: { (path:NSURL!, error:NSError!) -> Void in
println("\(path)")
println("\(error)")
})
}
}
}
}
Just Convert Below code to Swift. Below code are written in Objective-C. You just need to create IPTC or TIFF dictionary. Add value with suitable IPTC/TIFF key and write dictionary data(Meta Data) on image.
- (void) imagePickerController: (UIImagePickerController *)picker didFinishPickingMediaWithInfo: (NSDictionary *)info
{
UIImage *image = info[UIImagePickerControllerOriginalImage];
//Here We Get current system date and time and store as a description of photo
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSLog(#"Date Formatter : %#",[dateFormatter stringFromDate:[NSDate date]]);
//hh:mm:ss
NSDateFormatter *timeFormatter=[[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"hh:mm:ss"];
NSLog(#"time Formatterr : %#",[timeFormatter stringFromDate:[NSDate date]]);
//ADD IPTC Dictionary Data as a META DATA
NSMutableDictionary *iptcDict = [NSMutableDictionary dictionary];
[iptcDict setValue:[[DataEngine sharedInstance] getAlbumName] forKey:(NSString *)kCGImagePropertyIPTCObjectTypeReference]; //folder name
[iptcDict setValue:#“Renish Dadhaniya - 101" forKey:(NSString *)kCGImagePropertyIPTCObjectAttributeReference]; //add Image ID -get using query from database
[iptcDict setValue:[NSString stringWithFormat:#“Renish Sweet Memory "forKey:(NSString *)kCGImagePropertyIPTCObjectName]; //Add Image name
[iptcDict setValue:[dateFormatter stringFromDate:[NSDate date]]forKey:(NSString *)kCGImagePropertyIPTCDateCreated]; //Add Image Date
[iptcDict setValue:[timeFormatter stringFromDate:[NSDate date]]forKey:(NSString *)kCGImagePropertyIPTCTimeCreated]; //Add Image Time
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:iptcDict forKey:(NSString *)kCGImagePropertyIPTCDictionary];
//Get Iamge Url
__block NSURL *imageAssestURL = nil;
[asSetLib writeImageToSavedPhotosAlbum:image.CGImage metadata:dict completionBlock:^(NSURL* assetURL, NSError* error) {
if (error) {
NSLog(#"Image could not be safed to the assets library: %#", error);
imageAssestURL = nil;
}
else {
NSLog( #"Image safed successfully to assetURL: %#", assetURL);
imageAssestURL = assetURL;
}
}];
[picker dismissViewControllerAnimated:YES completion:nil];
}

Best way to persist an array of images?

I'm looking for a way to persist images to an array (or similar) that can be accessed after the app has closed an relaunched -- sorting the images by date is also required. I'm currently able to store the the images to the app's NSDocumentDirectory with the following code:
-(NSString *)currentDateandTime
{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MMddyyyy_HHmmss"];
NSString *dateString = [dateFormat stringFromDate:today];
return dateString;
}
-(void)saveImageToDocuments
{
NSData *imageData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *date = [self currentDateandTime];
NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_image.png",date]];
}
This means I've got images where the date/time is in the filenames of the image. What is the best way to go about storing these images in an array or dictionary AND sorting them by date/time. Thanks for reading!
I would save the file names and dates in a plist file which is an array of dictionaries of format: #{ #"filename" : imageFileName, #"date": imageDate }.
When you load that plist into an NSArray, you can easily sort it by date by specifying your own comparison method. e.g:
NSArray *filenames = [[NSArray alloc] initWithContentsOfFile:filePath];
NSArray *sortedFilenames = [filenames sortedArrayUsingComparator:
^NSComparisonResult(NSDictionary *dict1, NSDictionary *dict2)
{
NSDate *date1 = dict1[#"date"];
NSDate *date2 = dict2[#"date"];
return [date1 compare:date2];
}
Store the image data and the dates in some dictionaries, then store those dictionaries in an array, then use NSKeyedArchiver to archive the array.
[NSKeyedArchiver archiveRootObject:imageDictionary toFile:#"imagesArray"];
Then when you want to retrieve it:
NSArray * retrievedImages = [NSKeyedUnarchiver unarchiveObjectWithFile:#"imagesArray"];
Then just compare the dates in the various dictionaries in the retrieved array.

How to get iTunes Library top 10 song by playcount within recent 5days?

I'm trying to fetch iTunes library in ios.
And trying to retrieve top 10 playcount song in 5days.
Could you tell me how to do? Here's my code.
MPMediaPropertyPredicate is not right answer...I guess.
MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSLog(#"Logging items from a generic query...");
NSArray *itemsFromGenericQuery = [everything items];
for (MPMediaItem *song in itemsFromGenericQuery) {
NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
NSString *artistName = [song valueForProperty:MPMediaItemPropertyArtist];
NSString *lastPlayeddate = [song valueForProperty:MPMediaItemPropertyLastPlayedDate];
NSString *playCount = [song valueForProperty:MPMediaItemPropertyPlayCount];
NSLog (#"%#", songTitle);
text.text = [NSString stringWithFormat:#"%#\n%# %# %# %#", text.text, songTitle, artistName, lastPlayeddate, playCount];
}
All the best.
Apparently, play count is considered a "user defined" key, and therefore cannot be used in MPMediaPropertyPredicate
See http://developer.apple.com/library/ios/documentation/mediaplayer/reference/MPMediaItem_ClassReference/Reference/Reference.html#//apple_ref/doc/uid/TP40008211-CH1-SW38
You will have to iterate the songs and retrieve these properties manually.
enumerateValuesForProperties:usingBlock: is probably your most efficient option here.
http://developer.apple.com/library/ios/documentation/mediaplayer/reference/MPMediaEntity_ClassReference/Reference/Reference.html#//apple_ref/occ/instm/MPMediaEntity/enumerateValuesForProperties:usingBlock:

Log Accelerometer data to a file on Iphone IOS

Hi I am trying to write to a file from the accelerometer data. Here is my code:
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
//xax.text = [NSString stringWithFormat:#"X:[%2.6f]",acceleration.x];
//yax.text = [NSString stringWithFormat:#"Y:[%2.6f]",acceleration.y];
//zax.text = [NSString stringWithFormat:#"Z:[%2.6f]",acceleration.z];
NSString *acc_x = [[NSString alloc] initWithFormat:#"X:[%2.6f]",acceleration.x];
NSString *acc_y = [[NSString alloc] initWithFormat:#"Y:[%2.6f]",acceleration.y];
NSString *acc_z = [[NSString alloc] initWithFormat:#"Z:[%2.6f]",acceleration.z];
xax.text = acc_x;
yax.text = acc_y;
zax.text = acc_z;
[acc_x release];
[acc_y release];
[acc_z release];
//wfm == 2 //Initialization of Appending to the file
if (wfm == 2)
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *txtFileName = [[NSString alloc] initWithFormat:#"tmp/%#.txt",txtName.text];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:txtFileName];
//NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:#"tmp/acc_w_trial2.txt"];
//Current Contents of the file
NSString *fileCurrent = [[NSString alloc] initWithContentsOfFile:fileName];
//Date and Time of each Accelerometer Data
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd 'at' HH:mm:ss:SSS"];
NSDate *date = [NSDate date];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSString *msg = [[NSString alloc] initWithFormat:#"%#%# %#%#%# \n",fileCurrent,formattedDateString,xax.text,yax.text,zax.text];
//Convert NSstring to NSData
NSData* data=[msg dataUsingEncoding: [NSString defaultCStringEncoding]];
//bool fileCreationSuccess = [fileManager createFileAtPath:fileName contents:data attributes:nil];
[fileManager createFileAtPath:fileName contents:data attributes:nil];
[msg release];
[dateFormatter release];
[fileCurrent release];
[txtFileName release];
}
}
I get the warning level 1 and level 2. Is there a way I can release the NSFileManager memory to prevent this from locking up?
Your handler method to collect accelerometer data seems not very performant. You are allocating the resources (memory, file) everytime which can take a long time.
You should allocate the needed resources only once (i.e. use dispatch_once) and keep the file open. Use a NSFileHandle (method fileHandleForWritingAtPath) in order to append the data at the end of the file.
Furthermore NSHomeDirectory() is not where you're supposed to save user data, as iOS apps are sandboxed.
Either use NSTemporaryDirectory() or write in the Documents or Library Folder. The following is from Apple's sample code, usually in application delegate class:
- (NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
You can try using an Autorelease Pool.

Resources