Remove image view on touch - iphone

I have some images in my image view and image name in my scrollview ,now i want to remove image and related name on click on image...... just click on image and name of image should be removed and image will also .
My code is here.......
-(void)imageViewTapped:(UITapGestureRecognizer*)sender
{
bool isFound = FALSE;
NSInteger foundIndex=0;
NSInteger index = sender.view.tag;
NSMutableDictionary *currentObject = [dataArray objectAtIndex:index];
NSLog(#"id 1: %#", [currentObject objectForKey:#"_ID"]);
for (NSMutableDictionary *object in nameDAtaArray)
{
NSInteger currentId = [[object objectForKey:#"_ID"] intValue];
NSLog(#"id 2: %d", currentId);
if([[currentObject objectForKey:#"_ID"] intValue] == currentId)
{
++point;
isFound = TRUE;
NSLog(#"view tag...%d",sender.view.tag);
[sender.view removeFromSuperview];
};
break;
}
foundIndex++;
}
if(!isFound)
{
point--;
}
else
{
[nameDAtaArray removeObjectAtIndex:foundIndex];
[self showNameLabelInScrollView];
[nameContainerScrollView setNeedsDisplay];
}
[self showpointlabel];
}
thanks in advance..

-(void)scrollViewsingleTappedInScrollMethod:(UITapGestureRecognizer *)recognizer{
imageview = (UIImageView *)recognizer.view;
//we select the image using tag.(contain many images)
if ([imageview tag] == 100) {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%#.png", fileName]];
NSError *error = nil;
if(![fileManager removeItemAtPath: fullPath error:&error]) {
NSLog(#"Delete failed:%#", error);
} else {
NSLog(#"image removed: %#", fullPath);
}
NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];
NSLog(#"Directory Contents:\n%#", [fileManager directoryContentsAtPath: appFolderPath]);
}
}
If u hide only then set only Alpha. like, imageview.alpha = 0;

Related

Memory issue on Loading images from Photo Library and sort them datewise

I am fetching images from my photo library and according to assets's date property , I am arranging those images in a different folders . What I want to do is to fetch the image from photo library , store them according to date . e.g. if fetched image is from 23rd April, store them in "April" folder . I am using WSAssetPickerController for this. Please help me in solving memory issue as my app crashes due to the memory issue on device, this works fine in simulator.
- (void)storePhotos:(NSArray *)assets {
int index = 0;
for (ALAsset *asset in assets) {
NSLog(#"Current asset :%# ",asset);
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"MMMM dd, yyyy"];
NSString *photoDate = [format stringFromDate:[asset valueForProperty:ALAssetPropertyDate]];
resourceDocPath = [resourceDocPath stringByAppendingPathComponent:photoDate];
// Create directory & Check directory
BOOL checkDir = [self createDocumentDirectory:resourceDocPath fileName:asset.defaultRepresentation.filename];
if (!checkDir) {
continue;
}
// Write image
NSString *writablePhotoPath = [resourceDocPath stringByAppendingPathComponent:asset.defaultRepresentation.filename];
[self writeImage:writablePhotoPath WithImage:asset.defaultRepresentation.fullScreenImage];
index++;
}
}
- (void)writeImage:(NSString*)pstrPhotoPath WithImage:(CGImageRef)pImage {
if (![[NSFileManager defaultManager] fileExistsAtPath:pstrPhotoPath]){
UIImage *image = [[UIImage alloc] initWithCGImage:pImage];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:pstrPhotoPath atomically:YES];
}
}
- (BOOL)createDocumentDirectory:(NSString*) pCurrentFolder fileName:(NSString*) pStrFileName {
if (![[NSFileManager defaultManager] fileExistsAtPath:pCurrentFolder]){
if ([self checkPhotoIsExistInDocument:pStrFileName]) {
return FALSE;
}
NSError* error;
if ([[NSFileManager defaultManager] createDirectoryAtPath:pCurrentFolder withIntermediateDirectories:NO attributes:nil error:&error]) {
// success
return TRUE;
} else {
NSLog(#"[%#] ERROR: attempting to write create MyFolder directory", [self class]);
NSAssert( FALSE, #"Failed to create directory maybe out of disk space?");
return TRUE;
}
return TRUE;
} else {
return TRUE;
}
}
- (BOOL)checkPhotoIsExistInDocument:(NSString*) pStrImageName {
NSString *bundleRoot = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;
while ((filename = [direnum nextObject] )) {
// NSLog(#"%#", filename);
if ([filename hasSuffix:pStrImageName]) {
return TRUE;
}
}
return FALSE;
}
Are you using ARC in your project? Because you have not released any objects which you are allocating and initializing.
resourceDocPath
format
image
bundleRoot
Should be released as soon as their use is over. Also if you can provide the logs of your application crash that would be very useful.

File search with specific Extension Objective c

I am working on some file manipulation in iPhone project. Where i need to search files of specific extension. One option is to manually process each file & directory to find.
My Question is, Is there any simple way to do that ?
Thanks
see using NSFileManager you can get the files and bellow the condition with you can get file with particular extension, Its work in Document Directory ..
-(NSArray *)findFiles:(NSString *)extension
{
NSMutableArray *matches = [[NSMutableArray alloc]init];
NSFileManager *manager = [NSFileManager defaultManager];
NSString *item;
NSArray *contents = [manager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] error:nil];
for (item in contents)
{
if ([[item pathExtension]isEqualToString:extension])
{
[matches addObject:item];
}
}
return matches;
}
use this array with your searched files.. get the return in NSArray type so use NSArray object to store this data...
i hope this helpful to you...
I have not found any thing which i could say is simple to do that & and finally i have to write my own code to do this. I am posting this here because maybe someone find this help full.
-(void)search{
#autoreleasepool {
NSString *baseDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSFileManager *defFM = [NSFileManager defaultManager];
BOOL isDir = YES;
NSArray *fileTypes = [[NSArray alloc] initWithObjects:#"mp3",#"mp4",#"avi",nil];
NSMutableArray *mediaFiles = [self searchfiles:baseDir ofTypes:fileTypes];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:#"playlist.plist"];
if(![defFM fileExistsAtPath:filePath isDirectory:&isDir]){
[defFM createFileAtPath:filePath contents:nil attributes:nil];
}
NSMutableDictionary *playlistDict = [[NSMutableDictionary alloc]init];
for(NSString *path in mediaFiles){
NSLog(#"%#",path);
[playlistDict setValue:[NSNumber numberWithBool:YES] forKey:path];
}
[playlistDict writeToFile:filePath atomically:YES];
[[NSNotificationCenter defaultCenter] postNotificationName:#"refreshplaylist" object:nil];
}
}
Now the recursive Method
-(NSMutableArray*)searchfiles:(NSString*)basePath ofTypes:(NSArray*)fileTypes{
NSMutableArray *files = [[[NSMutableArray alloc]init] autorelease];
NSFileManager *defFM = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *dirPath = [defFM contentsOfDirectoryAtPath:basePath error:&error];
for(NSString *path in dirPath){
BOOL isDir;
path = [basePath stringByAppendingPathComponent:path];
if([defFM fileExistsAtPath:path isDirectory:&isDir] && isDir){
[files addObjectsFromArray:[self searchfiles:path ofType:fileTypes]];
}
}
NSArray *mediaFiles = [dirPath pathsMatchingExtensions:fileTypes];
for(NSString *fileName in mediaFiles){
fileName = [basePath stringByAppendingPathComponent:fileName];
[files addObject:fileName];
}
return files;
}
What you need is a recursive method so that you can process sub-directories. The first of the following methods is public; the other private. Imagine they are implemented as static methods of a class called CocoaUtil:
CocoaUtil.h:
#interface CocoaUtil : NSObject
+ (NSArray *)findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder;
#end
CocoaUtil.m:
// Private Methods
#interface CocoaUtil ()
+ (NSArray *)_findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder
andSubFolder:(NSString *)subFolder;
#end
#implementation CocoaUtil
+ (NSArray *)findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder
{
return [CocoaUtil _findFilesWithExtension:extension
inFolder:folder
andSubFolder:nil];
}
+ (NSArray *)_findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder
andSubFolder:(NSString *)subFolder
{
NSMutableArray *found = [NSMutableArray array];
NSString *fullPath = (subFolder != nil) ? [folder stringByAppendingPathComponent:subFolder] : folder;
NSFileManager *fileman = [NSFileManager defaultManager];
NSError *error;
NSArray *contents = [fileman contentsOfDirectoryAtPath:fullPath error:&error];
if (contents == nil)
{
NSLog(#"Failed to find files in folder '%#': %#", fullPath, [error localizedDescription]);
return nil;
}
for (NSString *file in contents)
{
NSString *subSubFolder = subFolder != nil ? [subFolder stringByAppendingPathComponent:file] : file;
fullPath = [folder stringByAppendingPathComponent:subSubFolder];
NSError *error = nil;
NSDictionary *attributes = [fileman attributesOfItemAtPath:fullPath error:&error];
if (attributes == nil)
{
NSLog(#"Failed to get attributes of file '%#': %#", fullPath, [error localizedDescription]);
continue;
}
NSString *type = [attributes objectForKey:NSFileType];
if (type == NSFileTypeDirectory)
{
NSArray *subContents = [CocoaUtil _findFilesWithExtension:extension inFolder:folder andSubFolder:subSubFolder];
if (subContents == nil)
return nil;
[found addObjectsFromArray:subContents];
}
else if (type == NSFileTypeRegular)
{
// Note: case sensitive comparison!
if ([[fullPath pathExtension] isEqualToString:extension])
{
[found addObject:fullPath];
}
}
}
return found;
}
#end
This will return an array containing the full path to every file with the specified file extension. Note that [NSString pathExtension] does not return the . of the file extension so be sure not to pass that in the extension parameter.
Yes we have direct method for NSArray below helps you
NSMutableArray *arrayFiles = [[NSMutableArray alloc] initWithObjects:#"a.png", #"a.jpg", #"a.pdf", #"h.png", #"f.png", nil];
NSLog(#"pathsMatchingExtensions----%#",[arrayFiles pathsMatchingExtensions:[NSArray arrayWithObjects:#"png", nil]]);
//my output is
"a.png",
"h.png",
"f.png"
Like this way you can find your specific file extension
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;
while ((filename = [direnum nextObject] )) {
if ([filename hasSuffix:#".doc"]) { //change the suffix to what you are looking for
[arrayListofFileName addObject:[filename stringByDeletingPathExtension]];
}
}
Use below code
NSArray *myFiles = [myBundle pathsForResourcesOfType:#"Your File extension"
inDirectory:nil];

How can I use iCloud to synchronize a .zip file between my apps?

Is it possible to upload a .zip file to iCloud, and then have it be synchronized across all of a user's iOS devices?
If so, how would I go about doing this?
If there is any File size limit, then also mention max. file size allowed.
This is how I synchronized zip files with iCloud .
Steps:
1) http://transoceanic.blogspot.in/2011/07/compressuncompress-files-on.html
. Refer this link to download zip api which is having code for zipping and unzipping folder.
2) Now all you need to play with NSData.
3) "MyDocument.h" file
#import <UIKit/UIKit.h>
#interface MyDocument : UIDocument
#property (strong) NSData *zipDataContent;
#end
4)
#import "MyDocument.h"
#implementation MyDocument
#synthesize zipDataContent;
// Called whenever the application reads data from the file system
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
self.zipDataContent = [[NSData alloc] initWithBytes:[contents bytes] length:[contents length]];
[[NSNotificationCenter defaultCenter] postNotificationName:#"noteModified" object:self];
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
return self.zipDataContent;
}
#end
5) Now somewhere in your app you need to zip folder and sync with icloud.
-(BOOL)zipFolder:(NSString *)toCompress zipFilePath:(NSString *)zipFilePath
{
BOOL isDir=NO;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pathToCompress = [documentsDirectory stringByAppendingPathComponent:toCompress];
NSArray *subpaths;
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:pathToCompress isDirectory:&isDir] && isDir){
subpaths = [fileManager subpathsAtPath:pathToCompress];
} else if ([fileManager fileExistsAtPath:pathToCompress]) {
subpaths = [NSArray arrayWithObject:pathToCompress];
}
zipFilePath = [documentsDirectory stringByAppendingPathComponent:zipFilePath];
//NSLog(#"%#",zipFilePath);
ZipArchive *za = [[ZipArchive alloc] init];
[za CreateZipFile2:zipFilePath];
if (isDir) {
for(NSString *path in subpaths){
NSString *fullPath = [pathToCompress stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
[za addFileToZip:fullPath newname:path];
}
}
} else {
[za addFileToZip:pathToCompress newname:toCompress];
}
BOOL successCompressing = [za CloseZipFile2];
if(successCompressing)
return YES;
else
return NO;
}
-(IBAction) iCloudSyncing:(id)sender
{
//***** PARSE ZIP FILE : Pictures *****
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
if([self zipFolder:#"Pictures" zipFilePath:#"iCloudPictures"])
NSLog(#"Picture Folder is zipped");
ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:#"iCloudPictures.zip"];
mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:#"iCloudPictures"];
NSURL *u = [[NSURL alloc] initFileURLWithPath:zipFilePath];
NSData *data = [[NSData alloc] initWithContentsOfURL:u];
// NSLog(#"%# %#",zipFilePath,data);
mydoc.zipDataContent = data;
[mydoc saveToURL:[mydoc fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
{
if (success)
{
NSLog(#"PictureZip: Synced with icloud");
}
else
NSLog(#"PictureZip: Syncing FAILED with icloud");
}];
}
6) You can unzip data received from iCloud like this.
- (void)loadData:(NSMetadataQuery *)queryData {
for (NSMetadataItem *item in [queryData results])
{
NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
MyDocument *doc = [[MyDocument alloc] initWithFileURL:url];
if([filename isEqualToString:#"iCloudPictures"])
{
[doc openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(#"Pictures : Success to open from iCloud");
NSData *file = [NSData dataWithContentsOfURL:url];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *zipFolder = [documentsDirectory stringByAppendingPathComponent:#"Pics.zip"];
[[NSFileManager defaultManager] createFileAtPath:zipFolder contents:file attributes:nil];
//NSLog(#"zipFilePath : %#",zipFolder);
NSString *outputFolder = [documentsDirectory stringByAppendingPathComponent:#"Pictures"];//iCloudPics
ZipArchive* za = [[ZipArchive alloc] init];
if( [za UnzipOpenFile: zipFolder] ) {
if( [za UnzipFileTo:outputFolder overWrite:YES] != NO ) {
NSLog(#"Pics : unzip successfully");
}
[za UnzipCloseFile];
}
[za release];
NSError *err;
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:outputFolder error:&err];
if (files == nil) {
NSLog(#"EMPTY Folder: %#",outputFolder);
}
// Add all sbzs to a list
for (NSString *file in files) {
//if ([file.pathExtension compare:#".jpeg" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
NSLog(#" Pictures %#",file);
// NSFileManager *fm = [NSFileManager defaultManager];
// NSDictionary *attributes = [fm fileAttributesAtPath:[NSString stringWithFormat:#"%#/%#",documentsDirectory,file] traverseLink:NO];
//
// NSNumber* fileSize = [attributes objectForKey:NSFileSize];
// int e = [fileSize intValue]; //Size in bytes
// NSLog(#"%#__%d",file,e);
}
}
else
{
NSLog(#"Pictures : failed to open from iCloud");
[self hideProcessingView];
}
}];
}
}
}
In order to enabling Document storage in iCloud your "document" needs to be encapsulated in a UIDocument object.
Because UIDocument links to a file URL, you can easily create a UIDocument pointing to file://myzipfile.zip and then upload a zip document to iCloud.
I hope this helps
Probably this tutorial can help you more:
http://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1

initWithDocPath not found

it shows me warning that initWithDocPath not found when i want to get private directory content..
+ (NSMutableArray *)loadScaryBugDocs {
NSString *documentsDirectory = [VideoDatabase getPrivateDocsDir];
NSError *error;
NSArray *files =[NSFileManagerdefaultManager]contentsOfDirectoryAtPath:documentsDirectory error:&error];
if (files == nil) {
return nil;
}
NSMutableArray *retval = [NSMutableArray arrayWithCapacity:files.count];
for (NSString *file in files) {
if ([file.pathExtension compare:#"scarybug" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file];
VideoNotepadViewController *doc = [[[VideoNotepadViewController alloc] initWithDocPath:fullPath] autorelease];
//shows warning here
[retval addObject:doc];
}
}
return retval;
}
You need to implement the initWithDocPath: method in VideoNotepadViewController. Apple doesn't provide a method by that name.

Trying to save images in ipad app bundle from photo library

-(IBAction)saveImage{
NSMutableArray *dictWords= [[NSMutableArray alloc]initWithObjects:#"TIGER",#"CAT", #"ROSE", #"ELEPHANT",#"MOUSE IS LOOKING FOR THE CHEESE",#"KITE",#"CAR",#"AEROPLANE",#"MANGO",#"FRUITS ARE FALLING FROM THE TREE",#"MOUNTAIN",#"BIRDS ARE FLYING",#"IGLOO",#"THIS HOUSE IS BUILT OF WOODS",#"BANANA",#"RAINBOW",#"TRAIN",#"DADDY DRINKS JUICE",#"UMBRELLA",#"GOAT",#"CAT JUMPS HIGH",#"DOG RUNS FAST",#"BUS",#"GIRL IS CRYING",#"STARS",#"DOLPHIN",#"BOYS ARE PLAYING FOOTBALL",#"GLASS IS FULL OF WATER",#"SHIP",#"SNOWFALL",#"GHOST",#"RABBIT",#"WATERMELON",#"SPIDERMAN",#"DINOSAUR",#"MICKEY MOUSE",#"MONKEY IS SITTING ON A TREE",#"PEACOCK",#"LIGHTNING",#"HEN LAYS EGGS",nil];
NSString *path=[[NSBundle mainBundle] pathForResource:[youSaid text] ofType:#"png" inDirectory:#"Image"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i=0 ; i<[assets count]; i++) {
if (i<[dictWords count]) {
[dict setObject:[[[assets objectAtIndex:i] defaultRepresentation] url] forKey:[NSString stringWithFormat:#"%#",[dictWords objectAtIndex:i]]];
NSLog(#"diccount:%d",[dict count]);
}
}
NSURL *imageurl = [dict objectForKey:[youSaid text]];
//NSLog(#"text:%#",[youSaid text]);
//Getting asset from url
typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
//Setting asset image to image view according to the image url
[imageview setImage:[UIImage imageWithCGImage:iref]];
youSaid.text = [NSString stringWithFormat:#"%#",imageurl];
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"Error, cant get image - %#",[myerror localizedDescription]);
};
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:imageurl resultBlock:resultblock failureBlock:failureblock];
UIImage *image=[[UIImage alloc]initWithContentsOfFile:path];
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", youSaid.text]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image
NSLog(#"image saved");
}
#end
This is the following code i wrote but i am not able to save images.i am only able to sane an image known as NULL.png .please suggest the changes to save all the pics in my library to bundle.
Thanks,
Christy
Sample Code
- (void) openPhotoLibrary {
NSLog(#"openPhotolibrary");
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
if (self.picker != nil) {
NSLog(#"releasing self.picker...");
[self.picker release];
}
self.picker = [[UIImagePickerController alloc] init];
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//self.picker.allowsImageEditing = YES;
[self.picker presentModalViewController:self.picker animated:YES];
self.picker.delegate = self;
[[[CCDirector sharedDirector] openGLView] addSubview:self.picker.view];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)currentPicker {
NSLog(#"imagePickerControllerDidCancel");
// hide the self.picker if user cancels picking an image.
[currentPicker dismissModalViewControllerAnimated:YES];
self.picker.view.hidden = YES;
[self.picker.view removeFromSuperview];
}
- (void)imagePickerController:(UIImagePickerController *)currentPicker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self saveImage:image withImageName:#"myPhoto"];
}
//saving an image
- (void)saveImage:(UIImage*)image withImageName:(NSString*)imageName {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
NSLog(#"image saved");
}
This code its working for me try it may be its helps you
-(IBAction)PhotoLibraryButtonClicked:(id)sender{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:imagePicker animated:YES];
}
else{
[self displaysorceError];
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//[self.popoverrcontroller dismissPopoverAnimated:true];
//[popoverrcontroller release];
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// UIImage *rote = [image rotateInDegrees:219.0f];
img.image = image;
if(newMedia)
UIImageWriteToSavedPhotosAlbum(image, nil,nil, nil);
}else if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
//not available vidio
}
}
-(IBAction)saveImageIn:(id)sender{
NSData *imageData = UIImagePNGRepresentation(img.image);
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#" %d.png",img.image]];
[fileMan createFileAtPath:fullPathToFile contents:imageData attributes:nil];
UIAlertView *alt = [[UIAlertView alloc]
initWithTitle:#"Thank You"
message:#"Image Save In Directory"
delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alt show];
[alt release];
}
thank you..:)Neet