2011-01-27 13 views

risposta

5

È necessario utilizzare UIImagePickerController.

picker.sourceType = UIImagePickerControllerSourceTypeCamera; 

si deve implementare il metodo imagePickerController:didFinishPickingMediaWithInfo:UIImagePickerControllerDelegate e quindi memorizzare l'UIImage a dove si vuole, con qualsiasi nome file che si desidera, con metodi NSFileManager.

+0

come aprire fotocamera in che ... Puoi pubblicare qualche esempio codice ... –

+0

leggi la documentazione, contiene i codici campione – KingofBliss

+0

ancora una domanda .. come possiamo caricare immagini/audio/video su server in iphone ..? puoi dare qualche link utile ....? –

0
picker.sourceType = UIImagePickerControllerSourceTypeCamera; 

questo codice attiverà fotocamera del dispositivo ..

+0

- (IBAction) grabImage: (id) mittente { \t UIImagePickerController * picker = [[UIImagePickerController alloc] init]; \t picker.delegate = self; \t picker.allowsEditing = YES; \t picker.sourceType = UIImagePickerControllerSourceTypeCamera; \t [auto presenteModalViewController: selettore animato: SÌ]; \t [rilascio picker]; } – nik

+0

un'altra domanda..come possiamo caricare immagini/audio/video su server in iphone ..? Puoi dare qualche link utile ....? –

+0

@kuldeep convertirli in NSData e quindi caricare nel server – KingofBliss

8

EDIT: 15 mar 2016 - Ecco una versione veloce della mia risposta precedente, se siete alla ricerca per la versione Objective-C Avrete trovalo qui sotto

- SWIFT -

Prima conforme al protocollo UIImagePickerControllerDelegate e il protocollo UINavigationControllerDelegate

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate 

lancio l'immagine picker

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

implementare i metodi delegato per UIImagePickerDelegate protocollo

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: aggiornato per verificare se fotocamera è disponibile prima di tentare di lanciarlo. Aggiunto anche il codice che mostra come salvare una foto png nella cartella dei documenti all'interno della sandbox dell'app.

Provatelo (questo presuppone l'utilizzo di ARC).

Nel file .h conformi al protocollo delegato:

@interface MyViewController : UIViewController <UINavigationControllerDelegate,UIImagePickerControllerDelegate> 

Nel file .m lanciare il selettore di immagini (telecamera):

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

quindi implementare i protocolli delegato per gestire una l'utente annulla l'evento o salva/modifica/ecc. 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]; 
} 

anche aggiunto IN EDIT: Questi sono i metodi a cui fa riferimento è la classe di utilità per ottenere il percorso del documento e data/ora di

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

// Per Aprire Galleria

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

// For Open Fotocamera

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

Ecco una versione aggiornata della risposta di digitalHound che funziona per Swift 3.

azione funzione Launch fotocamera:

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

} 

Le Funzioni Delegate:

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 
    } 

Questo è ciò che ha funzionato per me.

0

Fase 1: Conferma per UIImagePickerControllerDelegate , UINavigationControllerDelegate

Fase 2: (iOS 10+) Aggiungi questo come chiave per il file info.plist chiave: Privacy - Camera Utilizzo Descrizione
valore: #Your messaggio

Fase 3: e questo nella vostra @IBAction

if UIImagePickerController.isSourceTypeAvailable(.camera) { 
     var imagePicker = UIImagePickerController() 
     imagePicker.delegate = self 
     imagePicker.sourceType = .camera 
     imagePicker.allowsEditing = false 
     self.present(imagePicker, animated: true, completion: nil) 
    } 
Problemi correlati