Cómo abrir la cámara en la aplicación para el iPhone ... Al igual que el uso de imagepickerview podemos abrir la library..how para abrir la aplicación de la cámara para que podamos tomar la foto ..abertura de aplicación para el iPhone programáticamente
Respuesta
Es necesario use UIImagePickerController.
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
Usted tiene que poner en práctica el método de UIImagePickerControllerDelegate
imagePickerController:didFinishPickingMediaWithInfo:
y luego almacenar el UIImage al lugar que desee, con cualquier nombre de archivo que desea, utilizando métodos NSFileManager.
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
este código se activará la cámara del dispositivo ..
- (IBAction) grabImage: (id) remitente { \t UIImagePickerController * selector = [[UIImagePickerController alloc] init]; \t picker.delegate = self; \t picker.allowsEditing = YES; \t picker.sourceType = UIImagePickerControllerSourceTypeCamera; \t [self presentModalViewController: selector animado: SÍ]; \t [liberación del selector]; } – nik
una pregunta más ... ¿cómo podemos subir imágenes/audio/video al servidor en iphone ...? ¿Puede darnos algún enlace útil ...? –
@kuldeep convertirlos a NSData y luego cargar al servidor – KingofBliss
EDITAR: 15 Marzo, 2016 - Esta es una versión rápida de mi respuesta anterior, si usted está buscando para la versión de Objective-C se le encuentra abajo
- SWIFT -
En primer lugar se ajusta al protocolo y el protocolo UIImagePickerControllerDelegate UINavigationControllerDelegate
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
lanzamiento de la imagen selector
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)
}
}
poner en práctica los métodos de delegado para el protocolo 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 -
EDIT: Actualización para comprobar si la cámara está disponible antes de intentar poner en marcha. También se agregó un código que muestra cómo guardar una foto PNG en la carpeta de documentos dentro del entorno limitado de la aplicación.
Dale una oportunidad (esto supone el uso de ARC).
En el archivo .h se ajustan al protocolo delegado:
@interface MyViewController : UIViewController <UINavigationControllerDelegate,UIImagePickerControllerDelegate>
En el archivo .m lanzar el selector de imágenes (cámara):
-(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;
}
}
luego implementar los protocolos de delegado para manejar una el usuario cancela el evento o guarda/edita/etc. la foto.
-(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];
}
incluso agregó EDIT: Éstos son los métodos que se hace referencia es la clase Utilidades para obtener la ruta del documento y la fecha/hora actual
+(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;
}
// Para Abrir Galería
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePickerController.delegate = self;
if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self presentViewController:imagePickerController animated:YES completion:nil];
}];
}
else{
[self presentViewController:imagePickerController animated:YES completion:nil];
}
// Para abrir Cámara
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePickerController.delegate = self;
if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self presentViewController:imagePickerController animated:YES completion:nil];
}];
}
else{
[self presentViewController:imagePickerController animated:YES completion:nil];
}
}
Aquí hay una versión actualizada de la respuesta de digitalHound que funciona para Swift 3.
Acción función de cámara de lanzamiento:
func actionLaunchCamera()
{
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
{
let imagePicker:UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = true
self.present(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)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
alert.view.tintColor = UIColor(red:0.37, green:0.66, blue:0.44, alpha:1.0)
self.present(alert, animated: true, completion: nil)
}
}
Las funciones de delegado:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// create a filepath with the current date/time as the image name
let savePath:URL = URL(fileURLWithPath: 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:Data = editedImg == nil ? UIImagePNGRepresentation(editedImg!)! : UIImagePNGRepresentation(originalImg!)! as Data
// write the image data to file
try! imgData.write(to: savePath, options: [])
// dismiss the picker
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// picker cancelled, dismiss picker view controller
self.dismiss(animated: true, completion: nil)
}
// added these methods simply for convenience/completeness
func documentsPath() ->String?
{
// fetch our paths
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.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:DateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
// get current date
let now:Date = Date()
// generate date string from now
let theDateTime = dateFormatter.string(from: now)
return theDateTime
}
Esto es lo que funcionó para mí.
Paso 1: Confirmar para UIImagePickerControllerDelegate , UINavigationControllerDelegate
Paso 2: (IOS 10+) Añadir esto como clave para su archivo info.plist clave: Privacidad - Cámara Uso Descripción
valor: #Your mensaje
Paso 3: y esto a su @IBAction
if UIImagePickerController.isSourceTypeAvailable(.camera) {
var imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
- 1. Muestra programáticamente el teclado en la aplicación para iPhone
- 2. Detectando programáticamente si hay una aplicación instalada en el iPhone
- 3. ¿Es posible silenciar programáticamente el iPhone?
- 4. Cómo generar JSON programáticamente utilizando el marco JSON para iPhone
- 5. ¿Apagar un iPhone programáticamente?
- 6. Mostrar el teclado del iPhone programáticamente
- 7. abertura situada en la carpeta complemento
- 8. iPhone: abre una url programáticamente
- 9. cómo ocultar el teclado programáticamente en iphone
- 10. Cliente de correo abierto de iPhone programáticamente
- 11. ¿Cómo borro el caché del navegador programáticamente en el iPhone?
- 12. ¿Cómo obtiene programáticamente el número de serie de un iPhone?
- 13. ¿Cambia el tema de la aplicación programáticamente?
- 14. iPhone - Eliminar barra de estado programáticamente
- 15. iPhone Event Kit: crear programáticamente un EKCalendar?
- 16. Cómo configurar CMake para crear una aplicación para el iPhone
- 17. Personalizar aplicación de iPhone para diferentes clientes
- 18. Almacenamiento local para la aplicación de iPhone
- 19. implementación inalámbrica de la aplicación para iPhone
- 20. Identificador único para una aplicación de iPhone
- 21. Alternativas a NSHost de aplicación para el iPhone
- 22. Hacer Actualización de una aplicación para el iPhone en vivo
- 23. aplicación para iPhone usando el entorno de desarrollo .NET?
- 24. Gráficos financieros para la aplicación de iPhone
- 25. Comparta mi aplicación de iPhone para probar
- 26. iPhone: Acceda a las notas de voz programáticamente
- 27. Inicia la aplicación de la brújula desde el interior de aplicación para el iPhone
- 28. desactivó programáticamente una aplicación predeterminada
- 29. Simplemente cambie el nombre del archivo ejecutable de la aplicación para una aplicación para iPhone
- 30. iPhone Cambiar el nombre de la aplicación
cómo abrir la cámara en la que ... ¿se puede publicar algunos ejemplos código ... –
lea la documentación, contiene ejemplos de códigos – KingofBliss
una pregunta más ... ¿cómo podemos subir imágenes/audio/video al servidor en iphone ...? ¿puede darnos algún enlace útil ...? –