Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

ios - How to select image from photo library and show the system camera interface within the app?

How can I let a user select a photo from the Apple Photos library? How do we show the system camera UI to allow the user to take a picture?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EDIT: March 15, 2016 - Here is a swift version of my prior answer, if you're looking for the objective-c version you'll find it below.

-- SWIFT --

First conform to the UIImagePickerControllerDelegate protocol and the UINavigationControllerDelegate protocol

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate

launch the image 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)
    }
}

implement the delegate methods for UIImagePickerDelegate protocol

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: Updated to check if camera is available before trying to launch it. Also added code showing how to save a png photo to the documents folder within the app sandbox.

Give this a try (this assumes using ARC).

In the .h file conform to the delegate protocol:

@interface MyViewController : UIViewController <UINavigationControllerDelegate,UIImagePickerControllerDelegate>

In the .m file launch the image picker (camera):

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

Then implement the delegate protocols to handle a user cancel event or save/edit/etc the photo.

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

ALSO ADDED IN EDIT: Here are the methods referenced it the Utilities class for getting the document path and current date/time

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...