I use the below code snippet to open the camera, click a photo and use the photo (when the two options, Retake and Use Photo, appear).
- (IBAction)openCamera
{
#autoreleasepool {
[imageSpinner stopAnimating];
[imageSpinner removeFromSuperview];
[cameralabel setText:#""];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType =
UIImagePickerControllerSourceTypeCamera;
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:NO completion:nil];
imagePicker=nil;
}
}
}
-(void)setImageSpinner
{
#autoreleasepool {
imageSpinner = nil;
imageSpinner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
imageSpinner.center = self.view.center;
[imageSpinner startAnimating];
[self.view addSubview:imageSpinner];
[self.view bringSubviewToFront:imageSpinner];
}
}
- (void)viewDidLoad
{
[self openCamera];
[super viewDidLoad];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.navigationController setToolbarHidden:YES];
self.navigationItem.hidesBackButton = NO;
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
-(void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *savedImagePath;
#autoreleasepool {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"Image 1.jpeg"];
paths=nil;
documentsDirectory=nil;
[picker dismissViewControllerAnimated:NO completion:NULL];
[cameralabel setText:#"Please wait"];
[self setImageSpinner];
}
#autoreleasepool {
ManifestDocumentViewController *manifestVC = [self.storyboard instantiateViewControllerWithIdentifier:#"manifestImage"];
manifestVC.getTempFilePath = savedImagePath;
if ([screenName isEqualToString:#"Retake"])
{
manifestVC.screenName = #"Retake";
manifestVC.retakeFileID = retakeFileID;
manifestVC.retakeFilePath = retakeFilePath;
NSData *data = [NSData dataWithContentsOfFile:savedImagePath];
[data writeToFile:retakeFilePath atomically:YES];
data=nil;
}
else
{
manifestVC.screenName = #"Camera";
UIImage *image = info[UIImagePickerControllerOriginalImage];
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[imageData writeToFile:savedImagePath atomically:NO];
image=nil;
imageData=nil;
}
savedImagePath=nil;
[self.navigationController pushViewController:manifestVC animated:YES];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:NULL];
picker.delegate=nil;
picker=nil;
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
During a debugging session on iPhone 4s, the memory spikes up as shown by the memory usage under the Debug navigator. Attached along side is a screenshot of the Memory Usage comparison. The raise in 'Other Processes' is a matter of concern.
Received memory warning also appears among the displayed logs. After running the code a number of times the app crashes (The message 'Lost connection to iPhone'). This corresponds to a spike in the memory and the 'Free' memory being consumed completely.
Can the above code be optimised as far as possible to ensure that the memory usage gets reduced as much as possible.
Related
-(void)cameraAndPhotoAlbums{
self.actionSheet = [[UIActionSheet alloc] initWithTitle:#"title" delegate:self cancelButtonTitle:#"cancel" destructiveButtonTitle:nil otherButtonTitles:#"Photo album",#"camera", nil];
[self.actionSheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==0) {
UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:imagePicker animated:YES completion:nil];
} else if(buttonIndex==1) {
UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:imagePicker animated:YES completion:nil];
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
[picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerControllerDidCancel:(id)picker{
[picker dismissViewControllerAnimated:YES completion:nil];
}
But at the time of photo album selected photos will only perform the cancel but finish don't perform, tried this item anywhere to write all can't, I again open a project can go agent, a great god save stunned me..
Here is a sample code for you to study:
ViewController.h
#interface ViewController : UIViewController<UIImagePickerControllerDelegate>
{
UIImagePickerController * imagePicker;
}
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)setImageToImageView:(UIButton *)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSLog(#"%#",NSHomeDirectory());
imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Image Picker Delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
NSLog(#"Image picked");
self.imageView.image = [info valueForKey:#"UIImagePickerControllerOriginalImage"];
if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary)
{
NSData * data = UIImageJPEGRepresentation([info valueForKey:#"UIImagePickerControllerOriginalImage"], 0.5);
NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/image.JPEG"];
[data writeToFile:path atomically:true];
}
else
{
UIImageWriteToSavedPhotosAlbum([info valueForKey:#"UIImagePickerControllerOriginalImage"], nil, nil, nil);
}
[self dismissViewControllerAnimated:true completion:nil];
}
- (IBAction)setImageToImageView:(UIButton *)sender
{
if (sender.tag == 101)
{
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
else
{
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
[self presentViewController:imagePicker animated:true completion:nil];
}
#end
This code works, tested it on a device.
I have the code by which I can take a picture from the camera or from the gallery of the phone,
But I want to save the image in the core data that I find it difficult.
I read a lot about it and I'm not sure with the image as string or binary data
And how to save it and how to get it.
#property (strong) NSMutableArray *allPic;
#property (strong) NSManagedObject *Image;
#end
#implementation ViewController
-(NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Picture"];
self.allPic = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
}
-(void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)takePic:(id)sender {
// ALERT SHEET.
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//CAMERA
UIAlertAction *openCamrea = [UIAlertAction actionWithTitle:#"צלם" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
// If device has no camera.
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIAlertController *alertNoCamera = [UIAlertController alertControllerWithTitle:#"Error" message:#"Device has no camera" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];
[alertNoCamera addAction:ok];
[self presentViewController:alertNoCamera animated:YES completion:nil];
}
else// if have a camera.
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
}];
// GALLERY
UIAlertAction *openGallery = [UIAlertAction actionWithTitle:#"גלריה" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}];
[alert addAction:openCamrea];
[alert addAction:openGallery];
[self presentViewController:alert animated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//save image
{
I think right way will be saving file in directory and storing path to CoreData. Here is how I have achieved it:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
[self.view makeToast:#"Saving Captured Image!" duration:2.0f position:#"top"];
UIImage *image = info[UIImagePickerControllerOriginalImage];
[self performSelectorInBackground:#selector(saveImage:) withObject:image];
}
}
- (void) saveImage : (UIImage *) image {
// image detail
// NSData *data = UIImagePNGRepresentation(image);
NSData *data = UIImageJPEGRepresentation(image, 1.0f);
NSString *imagePath = [self pathForMedia:MediaTypeImage name:[self getImageName:data]];
//WRITE FILE
BOOL saved = [data writeToFile:imagePath atomically:YES];
if (!saved)
return;
//Now save: `imagePath` to core Data.
}
- (NSString *) getImageName : (NSData *) imageData {
return [NSString stringWithFormat:#"%#.%#",[self getUniqueId], [self contentTypeForImageData:imageData]];
}
- (NSString *) pathForMedia : (MediaType) type name : (NSString *) name{
NSString *foldername = [NSString stringWithFormat:#"/%#/%#", ((type == MediaTypeImage) ? #"Photos" : #"Videos"), name];
return [[self getUserDocumentDir] stringByAppendingPathComponent:foldername];
}
- (NSString *)contentTypeForImageData:(NSData *)data {
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return #"jpg";
case 0x89:
return #"png";
case 0x47:
return #"gif";
case 0x49:
break;
case 0x42:
return #"bmp";
case 0x4D:
return #"tiff";
}
return nil;
}
- (NSString *) getUniqueId {
CFUUIDRef unqiueId = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, unqiueId);
CFRelease(unqiueId);
return [(__bridge NSString*)string stringByReplacingOccurrencesOfString:#"-"withString:#""];
}
To Save Image in Core Data:
You can store images in Core Data using the Binary Data attribute type. However you should be aware of a few things:
Always convert your UIImage to a portable data format like png or jpg For example:
NSData *imageData = UIImagePNGRepresentation(image);
Enable "Allows external storage" on this attribute
Core Data will move the data to an external file if it hits a certain threshold. This file is also completely managed by Core Data, so you don't have to worry about it.
If you run into performance issues, try moving the Binary Data attribute to a separate entity.
You should abstract the conversion to NSData behind the interface of your NSManagedObject subclass, so you don't have to worry about conversions from UIImage to NSData or vice versa.
If your images are not strongly related to the entities in your model, I would suggest storing them outside of Core Data.
To Take Images from gallery or camera:
{
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Device has no camera"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[myAlertView show];
return;
}
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//if you want to take image from gallery
//picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
//picker.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentViewController:picker animated:YES completion:nil];
}
Hope this helps.
I have developed an app that allows the user to choose a video from the photo gallery and send it as an attachment in an email. I am able to choose a video from the gallery and proceed with sending the email but the video does not get attached with the email. There are no errors in the console.
ViewController.h:
#import <UIKit/UIKit.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <MessageUI/MessageUI.h>
#interface ViewController : UIViewController<UIImagePickerControllerDelegate, UINavigationControllerDelegate,MFMailComposeViewControllerDelegate>
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)choose:(id)sender;
#end
ViewController.m:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIAlertController *myAlertController = [UIAlertController alertControllerWithTitle:#"MyTitle"
message: #"MyMessage"
preferredStyle:UIAlertControllerStyleAlert ];
[self presentViewController:myAlertController animated:YES completion:nil];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)choose:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self performSelector:#selector(email:) withObject:chosenImage afterDelay:0.5];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)email:(UIImage *)choosenImage{
NSString *iOSVersion = [[UIDevice currentDevice] systemVersion];
NSString *model = [[UIDevice currentDevice] model];
NSString *version = #"1.0";
NSString *build = #"100";
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
[mailComposer setToRecipients:[NSArray arrayWithObjects: #"support#myappworks.com",nil]];
[mailComposer setSubject:[NSString stringWithFormat: #"MailMe V%# (build %#) Support",version,build]];
NSString *supportText = [NSString stringWithFormat:#"Device: %#\niOS Version:%#\n\n",model,iOSVersion];
supportText = [supportText stringByAppendingString: #"Please describe your problem or question."];
[mailComposer setMessageBody:supportText isHTML:NO];
NSData *data = UIImagePNGRepresentation(choosenImage);
[mailComposer addAttachmentData:data mimeType:#"image/png" fileName:#""];
[self presentViewController:mailComposer animated:YES completion:nil];
}
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Any suggestion/help would be much appreciated. Thank you.
You mentioned that you're trying to attach a video, and you've configured your UIImagePickerController to limit the mediaTypes to only videos. The problem then is that you're asking for the "edited image" in the "didFinishPickingMediaWithInfo" method:
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
The user did not pick an image - they picked a video. You need to use this instead:
NSURL *chosenVideoUrl = info[UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:chosenVideoUrl];
You can then pass the videoData to your email method and attach to the email. Be sure to update the mimeType from "image/png" to "video/mp4", as well.
If u need to attach both video and image you have write to code for both,but you written only for attaching an image.You can try the code below for getting both
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
if ([[info objectForKey:UIImagePickerControllerMediaType] isEqual:(NSString *)kUTTypeMovie]) {
NSString *videoURL = info[UIImagePickerControllerMediaURL];
[self emailImage:nil orVideo:videoURL];
}else {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self emailImage:chosenImage orVideo:nil];
}
[picker dismissViewControllerAnimated:YES completion:NULL];
}
UIImagePickerControllerMediaURL will return file url unlike UIImagePickerControllerEditedImage ,so can use NSData method dataWithContentsOfFile as bellow.
if (choosenImage) {
NSData *data = UIImagePNGRepresentation(choosenImage);
NSString *filename = [NSString stringWithFormat:#"Image_%#.png",TimeStamp];
[mailComposer addAttachmentData:data mimeType:#"image/png" fileName:filename];
[self presentViewController:mailComposer animated:YES completion:nil];
}else {
NSData *data = [NSData dataWithContentsOfFile:videoFile];
NSString *filename = [NSString stringWithFormat:#"Video_%#.mp4",TimeStamp];
[mailComposer addAttachmentData:data mimeType:#"video/mp4" fileName:filename];
[self presentViewController:mailComposer animated:YES completion:nil];
}
it will be good if you give a filename for the attachment it will be help full after it downloading.if you wish you can use a TimeStamp for that.
#define TimeStamp [NSString stringWithFormat:#"%f",[[NSDate date] timeIntervalSince1970] * 1000]
I am trying to upload my video file from my app to server and I am getting an exception in this code at uploadfilewitherror.
2014-08-22 15:55:49.092 [1990:907] -[__NSCFNumber localizedDescription]: unrecognized selector sent to instance 0x1f58fd60
2014-08-22 15:55:49.096 [1990:907] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber localizedDescription]: unrecognized selector sent to instance 0x1f58fd60'
* First throw call stack:
(0x326ed2a3 0x3a36b97f 0x326f0e07 0x326ef531 0x32646f68 0x74bdd 0x7328f 0x32f82d41 0x32f7a5c1 0x32ff2be3 0x3a78311f 0x3a7824b7 0x3a783dcb 0x326c0f3b 0x32633ebd 0x32633d49 0x361e62eb 0x34549301 0x6fac3 0x6fa50)
libc++abi.dylib: terminate called throwing an exception
Code is as below.
- (void)viewDidLoad
{
[super viewDidLoad];
ftpRequest = [[SCRFTPRequest alloc] init];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (void) recordVideo {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
picker.videoQuality = UIImagePickerControllerQualityTypeLow;
picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
picker.videoMaximumDuration = 60;
NSArray *sourceTypes =
[UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
if (![sourceTypes containsObject:(NSString *)kUTTypeMovie ]){
NSLog(#"Can't save videos");
}
[self presentModalViewController:picker animated:YES];
[picker release];
}
- (IBAction)startRecordClick:(id)sender {
[self recordVideo];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if (![mediaType isEqualToString:kUTTypeMovie])
return;
NSURL *mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSString* moviePath = mediaURL.absoluteString;
NSString *tempFilePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
NSLog(#"filepath %#",tempFilePath);
//try
ftpRequest = [[SCRFTPRequest alloc] initWithURL:[NSURL URLWithString:#"ftp://"]
toUploadFile:[[NSBundle mainBundle] pathForResource:#"tempFilePath" ofType:#"MOV"]];
ftpRequest.username = #"";
ftpRequest.password = #"";
// Specify a custom upload file name (optional)
ftpRequest.customUploadFileName = #"c.MOV";
// The delegate must implement the SCRFTPRequestDelegate protocol
ftpRequest.delegate = self;
[ftpRequest startRequest];
//try
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(tempFilePath))
{
UISaveVideoAtPathToSavedPhotosAlbum (tempFilePath, nil, nil, nil);
}
[picker dismissModalViewControllerAnimated: YES];
[picker release];
}
-(void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
NSLog(#"Finished with error: %#", error);
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissModalViewControllerAnimated: YES];
[picker release];
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}
- (void)ftpRequestDidFinish:(SCRFTPRequest *)request {
NSLog(#"Upload finished.");
}
- (void)ftpRequest:(SCRFTPRequest *)request didFailWithError:(NSError *)error {
NSLog(#"Upload failed: %#", [error localizedDescription]);
}
// Optional delegate methods
- (void)ftpRequestWillStart:(SCRFTPRequest *)request {
NSLog(#"Will transfer %lld bytes.", request.fileSize);
}
- (void)ftpRequest:(SCRFTPRequest *)request didWriteBytes:(NSUInteger)bytesWritten {
NSLog(#"Transferred: %d", bytesWritten);
}
- (void)ftpRequest:(SCRFTPRequest *)request didChangeStatus:(SCRFTPRequestStatus)status {
switch (status) {
case SCRFTPRequestStatusOpenNetworkConnection:
NSLog(#"Opened connection.");
break;
case SCRFTPRequestStatusReadingFromStream:
NSLog(#"Reading from stream...");
break;
case SCRFTPRequestStatusWritingToStream:
NSLog(#"Writing to stream...");
break;
case SCRFTPRequestStatusClosedNetworkConnection:
NSLog(#"Closed connection.");
break;
case SCRFTPRequestStatusError:
NSLog(#"Error occurred.");
break;
case SCRFTPRequestStatusNone:
NSLog(#"Error occurred - NONE.");
break;
}
}
#end
The provided code doesn't have any code base related to the FTP server.
didFinishPickingMediaWithInfo delegate will trigger when you use/done a video selection from your picker controller. If you want to uploads the video to FTP at the same time without any button action, just use the below code.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
//search for FTP code samples and upload this NSData to the FTP.
//save this video
NSString *moviePath = [mediaURL path];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath)) {
UISaveVideoAtPathToSavedPhotosAlbum (moviePath, nil, nil, nil);
}
}
If you want an other action on the button which sends the video to the ftp server, save the Asset URL and retrieve the video files using ALAsset Url, convert this to strems and upload to FTP.
This question already has an answer here:
Attaching an image to an email?
(1 answer)
Closed 8 years ago.
So i have created so far 2 text fields which, the text fields are connected to the mail composer and whatever the user writes in them is what comes up in the mail composer however i do not know how to do the same for the UIImageView, i want the user to choose a picture or take a picture and that be automatically added to the mail composer as well.
#interface xyzViewController ()
#end
#implementation xyzViewController
- (IBAction)savedata:(id)sender; {
NSString *savestring = _mytextview.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestring forKey:#"savedstring"];
[defaults synchronize];
NSString *savestring1 = _mytextview1.text;
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 setObject:savestring1 forKey:#"savedstring1"];
[defaults synchronize];
}
- (IBAction)loaddata:(id)sender; {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:#"savedstring"];
[_mytextview setText:loadstring];
[label setText:loadstring];
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
NSString *loadstring1 = [defaults objectForKey:#"savedstring1"];
[_mytextview1 setText:loadstring1];
}
- (IBAction)dismiss:(id)sender {
[sender resignFirstResponder];
}
- (IBAction)dismiss1:(id)sender {
[sender resignFirstResponder];
}
- (IBAction)takePhoto:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)selectPhoto:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)sendButton:(id)sender {
MFMailComposeViewController *mailContoller = [[MFMailComposeViewController alloc]init];
[mailContoller setMailComposeDelegate:self];
NSString *email = #"avip606#gmail.com";
NSString *email1 = #"avi_sp#hotmail.co.uk";
NSArray *emailArray = [[NSArray alloc]initWithObjects:email, email1, nil];
NSString *message = [#[_mytextview.text, _mytextview1.text] componentsJoinedByString: #"\n"];
[mailContoller setMessageBody:message isHTML:NO];
NSData *data = UIImagePNGRepresentation(_image);
[mailContoller addAttachmentData:data
mimeType:#"image/png"
fileName:#"image.png"];
[mailContoller setToRecipients:emailArray];
[mailContoller setSubject:#"IT WORKS!"];
[self presentViewController:mailContoller animated:YES completion:nil];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self mytextview] resignFirstResponder];
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Of course you can attach an image to a message, if you're using the MFMailComposeViewController class.
You just need to figure out how to use it's API of "addAttachmentData: mimeType: fileName:".
This related question might provide the answer you're looking for.