Saving picture from app - ios

I am trying to make my application open the camera app to take a save pictures.
from my application i am launching the camera application to take a picture with the following code:
-(IBAction)TakePhoto:(id)sender {
picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:NULL];
[picker release];
//save image??:
//UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo);
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:NULL];
}
My problem is that once the button is pressed, the camera comes out and allows me to take a picture. Once the picture is take, the image is shown and i have the option to "retake" or "use". My issue is that if i click "use" the image is not saved to the camera roll. Is there a possibility to save the image and eventually change the "use" button to say "save"?
Thank you for you help!

The photo isn't being saved because you never actually added the code to save the image to the didFinishPickingMediaWithInfo: delegate method. All you have to do is add the line that you commented out in TakePhoto: to this function and you will be able to save the photo to the camera roll. E.x:
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, NULL);
[self dismissViewControllerAnimated:YES completion:NULL];
}

static NSDateFormatter* dateFormatter;
- (NSString*) generateNameWithExtension: (NSString*) extension
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyyMMddHHmmssSSS";
});
NSDate* now = [NSDate date];
NSString* string = [dateFormatter stringFromDate:now];
string = [NSString stringWithFormat:#"%#.%#",string,extension];
return string;
}
- (NSString*) saveImage: (UIImage*) image WithExtension: (NSString*) extension
{
extension = [extension lowercaseString];
NSData* data;
if ([extension isEqualToString:#"png"])
{
data = UIImagePNGRepresentation(image);
}else if ([extension isEqualToString:#"jpg"]||[extension isEqualToString:#"jpeg"])
{
data = UIImageJPEGRepresentation(image, 1.0);
}else{
NSLog(#"Error save local image, Extension: (%#) is not recognized, use (PNG/JPG)",extension);
return nil;
}
NSString* imageName = [self generateNameWithExtension:extension];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *finalPath = [documents stringByAppendingPathComponent:imageName];
[data writeToFile:finalPath options:NSAtomicWrite error:nil];
return finalPath;
}
This code save image in folder you app. You can later use it: [UIImage imageWithContentsOfFile:finalPath]

Related

Can't Revert Back to Original Image After Using UIImagePickerController

I am having an interesting little problem using the uiimagepickercontroller and was wondering if anyone has any insight as to what might be happening. Users can take pictures with the camera or pick from the photo library until the cows come home as many times in a row as they like. My issue lies in allowing users to revert back to the original image that shipped with the app. Here is the flow:
Users go the the tableview which shows a thumbnail of the image.
Users navigate to the detail view which shows a larger view of the image.
Users can tap on the image in the detail view to bring up a custom alertcontroller with options to a) use the camera to take a picture, b) use a picture from their library, or c) revert back to the original image.
Users choose either option 'a' or option 'b' to either take a picture or use a picture from the photo library. IF they IMMEDIATELY change their mind about using one of those choices and want to just go back to using the original image, nothing happens! They can snap another picture or choose another image right away, but cannot revert back to the original image right away.
Reverting back to the original image DOES work perfectly when the app has been closed and then opened again. Sometimes it will work if you navigate around to other views within the app and then come back to the detail view where they just added their own image. By why the delay? I've searched around for two weeks but have not found anything resembling my problem or any solutions that help in any way (like reloading the headerview where image is sitting). Any thoughts?
Also I have figured out how to save the image to iCloud by using the documentation but cannot figure out how to retrieve them so there is no code for that. That is entirely different question. The same thing seems to occur even without that code.
Thanks for taking the time to look at this!
Here is some code:
-(void)bookImageTapped:(UIGestureRecognizer *)gesture
{
URBAlertView *changeImageAlertView = [[URBAlertView alloc] initWithTitle:#"Add A New Book Cover Image" message:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Use Camera", #"Open Gallery", #"Use Original Photo", nil];
[changeImageAlertView setHandlerBlock:^(NSInteger buttonIndex, URBAlertView *alertView) {
[self checkPermission];
if (PHAuthorizationStatusAuthorized)
{
if(buttonIndex == 0)
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
pickerController.delegate = self;
pickerController.allowsEditing = NO;
pickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:pickerController animated:YES completion:nil];
}];
[alertView hide];
}
else
{
NSLog(#"Camera not available");
[alertView hide];
}
}
else if (buttonIndex == 1)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
pickerController.delegate = self;
pickerController.allowsEditing = NO;
pickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:pickerController animated:YES completion:nil];
}];
[alertView hide];
}
else if (buttonIndex == 2)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self restoreOriginalPhoto];
}];
[alertView hide];
}
else
{
NSLog(#"button 2 cancel");
[alertView hide];
}
}
}];
[changeImageAlertView show];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
_book.largeBookImage = [info objectForKey:UIImagePickerControllerOriginalImage];
_book.largeBookImage = [self scaleImage:_book.largeBookImage toSize:CGSizeMake(120, 168)];
_bookImageView.image = _book.largeBookImage;
_book.wasNewImageAdded = YES;
_book.originalImageUsed = NO;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_book.largeBookImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
{
if ([[extension lowercaseString] isEqualToString:#"png"])
{
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
//Create a URL to the local file
NSURL *resourceURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]]];
if (resourceURL)
{
CKAsset *asset = [[CKAsset alloc] initWithFileURL:resourceURL];
//create a record object
CKRecord *bookCover = [[CKRecord alloc] initWithRecordType:#"Bookcover"];
//set the record's fields
bookCover[#"title"] = _book.title;
bookCover[#"bookImage"] = asset;
/* TO SAVE A RECORD */
//get the public database
CKContainer *appContainer = [CKContainer defaultContainer];
CKDatabase *publicDatabase = [appContainer publicCloudDatabase];
[publicDatabase saveRecord:bookCover completionHandler:^(CKRecord *bookCover, NSError *error) {
if (error)
{
//insert error handling
return;
}
//insert succesfully saved record code
NSLog(#"png record saved after using picker!");
}];
}
}
else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"])
{
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
//Create a URL to the local file
NSURL *resourceURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]]];
if (resourceURL)
{
CKAsset *asset = [[CKAsset alloc] initWithFileURL:resourceURL];
//create a record object
CKRecord *bookCover = [[CKRecord alloc] initWithRecordType:#"Bookcover"];
//set the record's fields
bookCover[#"title"] = _book.title;
bookCover[#"bookImage"] = asset;
/* TO SAVE A RECORD */
//get the public database
CKContainer *appContainer = [CKContainer defaultContainer];
CKDatabase *publicDatabase = [appContainer publicCloudDatabase];
[publicDatabase saveRecord:bookCover completionHandler:^(CKRecord *bookCover, NSError *error) {
if (error)
{
//insert error handling
return;
}
//insert succesfully saved record code
NSLog(#"jpg record saved after using picker!");
}];
}
}
else
{
NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
- (UIImage *) scaleImage:(UIImage*)image toSize:(CGSize)newSize
{
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
-(void)restoreOriginalPhoto
{
NSLog(#"restore photo called");
_book.originalImageUsed = YES;
_book.wasNewImageAdded = NO;
_bookImageView.image = _book.largeBookImage;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_book.largeBookImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
Here is the headerview with the imageview:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
_headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 26)];
_headerView.backgroundColor = [UIColor colorWithRed:8/255.0 green:46/255.0 blue:46/255.0 alpha:0.8];
if (section == 0)
{
_headerView.backgroundColor = [UIColor whiteColor];
_bookImageView = [[UIImageView alloc] initWithFrame:CGRectMake((tableView.frame.size.width - 120)/2, 6, 120, 168)];
_bookImageView.contentMode = UIViewContentModeScaleAspectFit;
if (_book.wasNewImageAdded)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
else
{
_bookImageView.image = _book.largeBookImage;
}
if(_book.originalImageUsed)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
UITapGestureRecognizer *bookImageTouched = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(bookImageTapped:)];
bookImageTouched.numberOfTapsRequired = 1;
[_bookImageView addGestureRecognizer:bookImageTouched];
_bookImageView.userInteractionEnabled = YES;
[_headerView addSubview:_bookImageView];
}
I finally figured it out! It seems that I was confusing xcode with my property names. The code ended up much simpler in the end.
In didFinishPickingMediaWithInfo I created a UIImage and then set it to the bookImageView.image. Later, when I wanted to be able to update the image back to the original image, then I could call the bundle asset, _book.largeBookImage. Voila! The image was able to update immediately.
The most pertinent code is posted below.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
_chosenImage = [[UIImage alloc] init];
_chosenImage = [info objectForKey:UIImagePickerControllerOriginalImage];
_bookImageView.image = _chosenImage;
_book.wasNewImageAdded = YES;
_book.originalImageUsed = NO;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_chosenImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
{
if ([[extension lowercaseString] isEqualToString:#"png"])
{
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
[self.tableView reloadData];
}
else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"])
{
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
[self.tableView reloadData];
}
else
{
//NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
-(void)restoreOriginalPhoto
{
_book.originalImageUsed = YES;
_book.wasNewImageAdded = NO;
_bookImageView.image = _book.largeBookImage;
_backgroundImage.image = _book.largeBookImage;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if (section == 0)
{
_bookImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 120, 168)];
_bookImageView.contentMode = UIViewContentModeScaleAspectFit;
_bookImageView.clipsToBounds = YES;
_bookImageView.layer.cornerRadius = 10.0f;
if (_book.wasNewImageAdded)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
else
{
_bookImageView.image = _book.largeBookImage;
}
if(_book.originalImageUsed)
{
_bookImageView.image = _book.largeBookImage;
}
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if(_book.originalImageUsed)
{
_bookImageView.image = _book.largeBookImage;
}
[self.tableView reloadData];
[self.tableView setContentOffset:CGPointZero animated:NO];
}

Want value of variable "fileName"

I have following method and code for getting image path,
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *representation = [myasset defaultRepresentation];
fileName = [representation filename];
NSLog(#"fileName : %#",fileName);
};
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:imageURL
resultBlock:resultblock
failureBlock:nil];
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.profileImg.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
profileImg.hidden = NO;
}
Now I want the value of fileName in another method that is,
- (IBAction)registerBtn:(UIButton *)sender {
NSLog(#"fileName path = %#", fileName);
}
In log result I get "null"
In my .h file I have implement the fileName variable.
So how can I get the value of this variable?
Your registerBtn method must be get called after you completely pick the image(i.e. your didFinishPickingMediaWithInfo`) get called.
Second thing if you just want to set unique name to your image then you should use time stamp.
You can get metadata of picked image in didFinishPickingMediaWithInfo like,
NSDictionary *metadata = info[UIImagePickerControllerMediaMetadata];
NSLog(#"%#", metadata);
then from meradata dictionary you can fetch value of DateTimeOriginal which will give pick date of media.

How to Save UIImage to a Transparent PNG?

I'm not sure where I'm doing the mistake, that's why I'd like to paste here some block of codes in order to find out what went wrong.
I have some PNG images that have transparent background and with using the block of codes below I'm trying save the selected image to application folder and NSUserDefault. And then I'm trying to call that saved image from application folder and display on UIBarButtonItem.
The purpose of saving to NSUserDefault as well is for testing.
So,
This is how I'm selecting the image.
- (IBAction)btnPressed:(UIButton *)sender
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
imgPicker.delegate = self;
imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imgPicker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeImage];
imgPicker.allowsEditing = NO;
[self presentViewController:imgPicker animated:YES completion:nil];
}
}
And with this I'm saving it to application using didFinishPickingMediaWithInfo;
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *) kUTTypeImage])
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//I believe this has the problem.
NSData *pngData = UIImagePNGRepresentation(image);
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"AppImages"];;
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *fileName = [stringPath stringByAppendingPathComponent:#"logoImage.png"];
[pngData writeToFile:fileName atomically:YES];
NSUserDefaults *logoUserDef = [NSUserDefaults standardUserDefaults];
[logoUserDef setValue:pngData forKey:#"logoImageData"];
}
}
Note: I don't have problem for the images that doesn't have transparent background.
And lastly this is how I'm calling it from both Application and NSUserDefault.
Using both NSUserDefaults and AppDirectory to see if they're showing different result.
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"logoImageData"])
{
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
UIImage *testing = [UIImage imageWithData:[user valueForKey:#"logoImageData"]];
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:#"logoImage" ofType:#"png" inDirectory:documentsDirectory];
UIBarButtonItem *logoBarButton = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:#selector(logoTapped)];
logoBarButton.imageInsets = UIEdgeInsetsMake(9, 0, 9, 90);
logoBarButton.image = [logoBarButton.image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[self.navigationItem setLeftBarButtonItems:#[logoBarButton]];
}
And method that returns UIImage from App Document.
-(UIImage *)loadImageWithFileName:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#/%#.%#", directoryPath, #"AppImages", fileName, [extension lowercaseString]]];
return result;
}
I don't know from where I'm doing wrong but as always, when I select image that has transparent background. It always convert its background to White. I need to save it as it is as transparent. I've searched a lot but couldn't find anything to solve this.
Any help is appreciated.
Solved the problem!
The block of codes that I posted with my question have nothing wrong. The problem was occurring from iTunes, when I synchronize images from my Mac to my iPhone iTunes convert them to JPEG and because of this images loses their transparency etc... and when I select images using my app, I was selecting them as JPEG without being aware and that's why I had these problems.
So I came up with a solution to have images via email. I just send them from my mac to iPhone with e-mail, and by this images didn't lose anything as a feature. After that when I used them in app as a right image, the program worked as it supposed to be.
You wrote
[logoUserDef setValue:pngData forKey:#"logoImageData"];
but I don't see where you synchronize. So add:
[logoUserDef synchronize];
I was able to preserve the transparency when saving an image to the Documents directory after using
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
[self dismissViewControllerAnimated:YES completion:nil];
UIImage *img = [info valueForKey:UIImagePickerControllerOriginalImage];
[yourButton setImage:img forState:UIControlStateNormal];
NSData *pngData = UIImagePNGRepresentation(img);
//do something with pngData
}
The key is the UIImagePickerControllerOriginalImage instead of other options like UIImagePickerControllerEditedImage.

How to upload Images on Server in ios? [duplicate]

This question already has answers here:
Send image to server as binary data
(2 answers)
Closed 9 years ago.
I want to upload image from UIImagePickerController.
I want to post my image to server from my iPad library.
I am not able to send the image to server. Any other options to do this?
I am doing this:
-(void)method_OpenImagePickerLibrary{
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
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image=[info objectForKey:UIImagePickerControllerEditedImage];
SelectPickerimageView.image=image;
NSData *imageData = UIImagePNGRepresentation(image);
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// Here is the file path for the image
filepath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"imagename.png"]];
[imageData writeToFile:filepath options:NSDataWritingAtomic error:nil];
[self dismissModalViewControllerAnimated:YES];
}
-(void)MethodUploadImage{
NSString *ftpUrl=#"ftp://yourftp Url";
NSString *strPortNumber=#"port Number";
NSString *strurlUpload=[NSString stringWithFormat:#"%#:%#",ftpUrl,strPortNumber];
NSString *getfilePath = filepath;
SCRFTPRequest *ftpRequest = [[SCRFTPRequest alloc] initWithURL:[NSURL URLWithString:strurlUpload] toUploadFile:getfilePath];
ftpRequest.username = #"Username";
ftpRequest.password = #"password";
ftpRequest.delegate = self;
/*
ftpRequest.didFinishSelector = #selector(uploadFinished:);
ftpRequest.didFailSelector = #selector(uploadFailed:);
ftpRequest.willStartSelector = #selector(uploadWillStart:);
ftpRequest.didChangeStatusSelector = #selector(requestStatusChanged:);
ftpRequest.bytesWrittenSelector = #selector(uploadBytesWritten:);*/
[ftpRequest startRequest];
}
These commented lines are giving me errors
Error 1: Undeclared selector
Error 2: Property
didFinishSelector,didFailSelector,willStartSelector,didChangeStatusSelector,bytesWrittenSelector
not found on SCRFtprequest delegate
Any idea or suggestion would be highly welcome.
Try using AFNetworking. It will surely make your life much easier.

upload photo from my iphone gallery

I am working on an application that needs its user to upload a photo for him, using iphone, how can i implement this : when click on the image in my personal information page, the gallery is opend to choose a photo. when the photo is chosen it must appear instead of the previous one (at first it is the default pic). Notice that, the path of this photo or the photo itself(i do not know) must be stored in the DataBase for the next login. Moreover, this photo must be transferred to the server in order to be shown on the website when the same user login on the web.
I did it using the following code, i can choose a photo but when i save the path i could not load the pic again. it is a white box !! there is no photo !!
-(void) pickPhoto
{
UIImagePickerController *picker ;
picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
{
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
else
{
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
}
[self presentViewController:picker animated:YES completion:nil];
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
if(!img)
img = [info objectForKey:UIImagePickerControllerOriginalImage];
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docDirPath stringByAppendingPathComponent:#"myImage.png"];
NSLog (#"File Path = %#", filePath);
UIButton *btn = (UIButton *)[self.tableView viewWithTag:2013];
[btn setBackgroundImage:img forState:UIControlStateNormal];
database= [[connectToDB alloc] init];
[database setDelegate:self];
[database saveUserPic:filePath ForUser:user.userId];
[self dismissViewControllerAnimated:YES completion:nil];
}
now to load the pic :
UIImage *img;
if(pic != nil)
img=[UIImage imageWithContentsOfFile:pic];
else
img= [UIImage imageNamed:#"business_userL.png"];
Any Help will be appreciated.!
UIImagePickerControllerReferenceURL will return reference to local storage of your selected image.
NSURL* localUrl = (NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL];
Now you can save this url in your database.
To retrieve the image : display image from URL retrieved from ALAsset in iPhone

Resources