2011-01-27 9 views

Respuesta

5

Es necesario use UIImagePickerController.

picker.sourceType = UIImagePickerControllerSourceTypeCamera; 

Usted tiene que poner en práctica el método de UIImagePickerControllerDelegateimagePickerController:didFinishPickingMediaWithInfo: y luego almacenar el UIImage al lugar que desee, con cualquier nombre de archivo que desea, utilizando métodos NSFileManager.

+0

cómo abrir la cámara en la que ... ¿se puede publicar algunos ejemplos código ... –

+0

lea la documentación, contiene ejemplos de códigos – KingofBliss

+0

una pregunta más ... ¿cómo podemos subir imágenes/audio/video al servidor en iphone ...? ¿puede darnos algún enlace útil ...? –

0
picker.sourceType = UIImagePickerControllerSourceTypeCamera; 

este código se activará la cámara del dispositivo ..

+0

- (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

+0

una pregunta más ... ¿cómo podemos subir imágenes/audio/video al servidor en iphone ...? ¿Puede darnos algún enlace útil ...? –

+0

@kuldeep convertirlos a NSData y luego cargar al servidor – KingofBliss

8

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; 
} 
0

// 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]; 
    } 
} 
0

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í.

0

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) 
    } 
Cuestiones relacionadas