РЕДАКТИРОВАТЬ: 15 марта 2016 г. - это быстрая версия моего предыдущего ответа, если вы ищете версию target-c, вы найдете ее ниже.
- SWIFT -
Сначала соответствует протоколу UIImagePickerControllerDelegate и протоколу UINavigationControllerDelegate
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
запустить средство выбора изображений
func actionLaunchCamera()
{
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
{
let imagePicker:UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
imagePicker.allowsEditing = true
self.presentViewController(imagePicker, animated: true, completion: nil)
}
else
{
let alert:UIAlertController = UIAlertController(title: "Camera Unavailable", message: "Unable to find a camera on this device", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: true, completion: nil)
}
}
реализовать методы делегата для протокола UIImagePickerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
// create a filepath with the current date/time as the image name
let savePath:String = self.documentsPath()! + "/" + self.presentDateTimeString() + ".png"
// try to get our edited image if there is one, as well as the original image
let editedImg:UIImage? = info[UIImagePickerControllerEditedImage] as? UIImage
let originalImg:UIImage? = info[UIImagePickerControllerOriginalImage] as? UIImage
// create our image data with the edited img if we have one, else use the original image
let imgData:NSData = editedImg == nil ? UIImagePNGRepresentation(editedImg!)! : UIImagePNGRepresentation(originalImg!)!
// write the image data to file
imgData.writeToFile(savePath, atomically: true)
// dismiss the picker
self.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
// picker cancelled, dismiss picker view controller
self.dismissViewControllerAnimated(true, completion: nil)
}
// added these methods simply for convenience/completeness
func documentsPath() ->String?
{
// fetch our paths
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
if paths.count > 0
{
// return our docs directory path if we have one
let docsDir = paths[0]
return docsDir
}
return nil
}
func presentDateTimeString() ->String
{
// setup date formatter
let dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
// get current date
let now:NSDate = NSDate()
// generate date string from now
let theDateTime = dateFormatter.stringFromDate(now)
return theDateTime
}
- OBJECTIVE-C -
РЕДАКТИРОВАТЬ: Обновлено, чтобы проверить, доступна ли камера, прежде чем пытаться ее запустить.Также добавлен код, показывающий, как сохранить фотографию png в папке документов в изолированной программной среде приложения.
Попробуйте сделать это (предполагается использование ARC).
В файле .h соответствуютпротокол делегата:
@interface MyViewController : UIViewController <UINavigationControllerDelegate,UIImagePickerControllerDelegate>
В файле .m запустите средство выбора изображений (камера):
-(void)actionLaunchAppCamera
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.allowsEditing = YES;
[self presentModalViewController:imagePicker animated:YES];
}else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Camera Unavailable"
message:@"Unable to find a camera on your device."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alert show];
alert = nil;
}
}
Затем реализуйте протоколы делегатов для обработки события отмены пользователя или сохранения / редактирования /и т.д. фотография.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//This creates a filepath with the current date/time as the name to save the image
NSString *presentTimeStamp = [Utilities getPresentDateTime];
NSString *fileSavePath = [Utilities documentsPath:presentTimeStamp];
fileSavePath = [fileSavePath stringByAppendingString:@".png"];
//This checks to see if the image was edited, if it was it saves the edited version as a .png
if ([info objectForKey:UIImagePickerControllerEditedImage]) {
//save the edited image
NSData *imgPngData = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerEditedImage]);
[imgPngData writeToFile:fileSavePath atomically:YES];
}else{
//save the original image
NSData *imgPngData = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage]);
[imgPngData writeToFile:fileSavePath atomically:YES];
}
[self dismissModalViewControllerAnimated:YES];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissModalViewControllerAnimated:YES];
}
ТАКЖЕ ДОБАВЛЕНО В РЕДАКТИРОВАНИЕ: Вот методы, на которые ссылается класс Utilities для получения пути к документу и текущей даты / времени
+(NSString *)documentsPath:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:fileName];
}
+(NSString *)getPresentDateTime{
NSDateFormatter *dateTimeFormat = [[NSDateFormatter alloc] init];
[dateTimeFormat setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
NSDate *now = [[NSDate alloc] init];
NSString *theDateTime = [dateTimeFormat stringFromDate:now];
dateTimeFormat = nil;
now = nil;
return theDateTime;
}