How to pick photo from camera roll - objective-c

I do not have a working version or idea how to get photos from your albums via PHPhotoLibrary or ALAssetsLibrary and install them in uicollectionviewcell like in instagram. I'm new to objective c :)
not install - add

I'm not sure what you mean by 'install to uicollectionviewcell' but here's how you would get photos from your album.
Ask for authorization
Show a UIImagePickerController (which is the default image picker view apple created for us)
Implement delegate methods to handle the picked image from the UIImagePickerController
Code would look as follows
Import statement:
#import <Photos/Photos.h>
Instantiate the image picker controller to show:
UIImagePickerController* imagePicker = [[UIImagePickerController alloc]init];
// Check if image access is authorized
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// Use delegate methods to get result of photo library -- Look up UIImagePicker delegate methods
imagePicker.delegate = self;
[self presentViewController:imagePicker animated:true completion:nil];
}
I believe this would usually prompt the user for access to the photo library, but it's always good practice to handle all cases of authorization prior to simply trying to show the imagepicker.
Ask for authorization:
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if(status == PHAuthorizationStatusNotDetermined) {
// Request photo authorization
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
// User code (show imagepicker)
}];
} else if (status == PHAuthorizationStatusAuthorized) {
// User code
} else if (status == PHAuthorizationStatusRestricted) {
// User code
} else if (status == PHAuthorizationStatusDenied) {
// User code
}
Finally implement delegate methods:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *image = info[UIImagePickerControllerOriginalImage];
// Do something with picked image
}
After you pick your image, you can add it to a newly instantiated UICollectionViewController. This is probably a whole other question and you would be better off reading documentation for this.
Note that this was introduced in IOS8(I think?), but the AL route code will be similar to the above.
Added
The photo library is just another database, but you still have to ask the user for authorization.
The steps would be as follows:
Ask for authorization
Retrieve photos from photo library
I haven't done #2 myself but there seems to be a way to do it.
Get all of the pictures from an iPhone photoLibrary in an array using AssetsLibrary framework?
From a cursory look, it seems like this is an asynchronous function so you should code accordingly (I would call the requestImage function inside each UICollectionViewCell if I were you).
Leave a comment if you run into any trouble.
Good Luck!

You need to declare delegate UIImagePickerControllerDelegate
like this..
hope its helps you a lot...
- (IBAction)captureImagehandler:(id)sender
{
if (! [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIAlertView *deviceNotFoundAlert = [[UIAlertView alloc] initWithTitle:#"No Device" message:#"Camera is not available"
delegate:nil
cancelButtonTitle:#"exit"
otherButtonTitles:nil];
[deviceNotFoundAlert show];
}
else
{
UIImagePickerController *cameraPicker = [[UIImagePickerController alloc] init];
cameraPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
cameraPicker.delegate =self;
// Show image picker
[self presentViewController:cameraPicker animated:YES completion:nil];
}
}

Related

extending UIImagePicker controller doesn't help to prevent rotation in io6

My application is set in info.plist to support only portrait mode.
However, the UIImagePickerController, rotates when the user rotates the screen to landscape.
Since in io6 the method shouldAutoRotate is not being called, I tried to extend it like this:
#interface NonRotatingUIImagePickerController : UIImagePickerController
#end
#implementation NonRotatingUIImagePickerController
-(NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationMaskPortrait;
}
#end
But it doesn't help. Any idea why?
And in the log I see the above methods being called. The UIImagePickerController at first is displayed in portrait and when the user rotates - it rotates as well instead of staying portrait.
I set the image picker in the view like this:
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (!self.imagePickerController) {
self.imagePickerController = [[NonRotatingUIImagePickerController alloc] init];
self.imagePickerController.delegate = self;
}
return self;
}
- (void)viewDidAppear:(BOOL)animated{
self.imagePickerController.showsCameraControls = NO;
CGRect imagePickerControllerFrame = CGRectMake(0, topBar.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - topBar.frame.size.height - bottomBar.frame.size.height);
self.imagePickerController.view.frame = imagePickerControllerFrame;
self.imagePickerController.allowsEditing = YES;
self.imagePickerController.view.clipsToBounds = YES;
self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera
[self.view.window addSubview:self.imagePickerController.view];
}
self.imagePickerController.view.frame = imagePickerControllerFrame;
// ...
[self.view.window addSubview:self.imagePickerController.view];
Well, that's all totally illegitimate. Apple makes this very clear in the docs:
This class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified
There is only one correct way to use an image picker controller that uses UIImagePickerControllerSourceTypeCamera - as a fullscreen presented view controller:
BOOL ok = [UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeCamera];
if (!ok) {
NSLog(#"no camera");
return;
}
NSArray* arr = [UIImagePickerController availableMediaTypesForSourceType:
UIImagePickerControllerSourceTypeCamera];
if ([arr indexOfObject:(NSString*)kUTTypeImage] == NSNotFound) {
NSLog(#"no stills");
return;
}
UIImagePickerController* picker = [UIImagePickerController new];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.mediaTypes = #[(NSString*)kUTTypeImage];
picker.delegate = self;
[self presentViewController:picker animated:YES completion:nil];
If you want to present a live picture-taking interface inside your own interface, use AVFoundation and the camera capture API that it gives you.
Downloadable working example here:
https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/ch30p816cameraCaptureWithAVFoundation/p683cameraCaptureWithAVFoundation/ViewController.m
Perhaps you'll consider this answer unhelpful; but I'll just paste a snippet from Apple's documentation:
Important: The UIImagePickerController class supports portrait mode only. This class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified, with one exception. You can assign a custom view to the cameraOverlayView property and use that view to present additional information or manage the interactions between the camera interface and your code.
UIImagePickerController Doc Link
Sorry to be a kill-joy. You should look for a replacement class. Quickie search shows there are a bunch.

Ask permission to access Camera Roll

I have a settings view where the user can choose switch on or off the feature 'Export to Camera Roll'
When the user switches it on for the first time (and not when he takes the first picture), I would like the app to ask him the permission to access the camera roll.
I've seen behavior in many app but can't find the way to do it.
I'm not sure if there is some build in method for this, but an easy way would be to use ALAssetsLibrary to pull some meaningless bit of information from the photo library when you turn the feature on. Then you can simply nullify what ever info you pulled, and you will have prompted the user for access to their photos.
The following code for example does nothing more than get the number of photos in the camera roll, but will be enough to trigger the permission prompt.
#import <AssetsLibrary/AssetsLibrary.h>
ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
[lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
NSLog(#"%zd", [group numberOfAssets]);
} failureBlock:^(NSError *error) {
if (error.code == ALAssetsLibraryAccessUserDeniedError) {
NSLog(#"user denied access, code: %zd", error.code);
} else {
NSLog(#"Other error code: %zd", error.code);
}
}];
EDIT: Just stumbled across this, below is how you can check the authorization status of your applications access to photo albums.
ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
if (status != ALAuthorizationStatusAuthorized) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Attention" message:#"Please give this app permission to access your photo library in your settings app!" delegate:nil cancelButtonTitle:#"Close" otherButtonTitles:nil, nil];
[alert show];
}
Since iOS 8 with Photos framework use:
Swift 3.0:
PHPhotoLibrary.requestAuthorization { status in
switch status {
case .authorized:
<#your code#>
case .restricted:
<#your code#>
case .denied:
<#your code#>
default:
// place for .notDetermined - in this callback status is already determined so should never get here
break
}
}
Objective-C:
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
switch (status) {
case PHAuthorizationStatusAuthorized:
<#your code#>
break;
case PHAuthorizationStatusRestricted:
<#your code#>
break;
case PHAuthorizationStatusDenied:
<#your code#>
break;
default:
break;
}
}];
Important note from documentation:
This method always returns immediately. If the user has previously granted or denied photo library access permission, it executes the handler block when called; otherwise, it displays an alert and executes the block only after the user has responded to the alert.
Since iOS 10, we also need to provide the photo library usage description in the info.plist file, which I described there. And then just use this code to make alert appear every time we need:
- (void)requestAuthorizationWithRedirectionToSettings {
dispatch_async(dispatch_get_main_queue(), ^{
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusAuthorized)
{
//We have permission. Do whatever is needed
}
else
{
//No permission. Trying to normally request it
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status != PHAuthorizationStatusAuthorized)
{
//User don't give us permission. Showing alert with redirection to settings
//Getting description string from info.plist file
NSString *accessDescription = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSPhotoLibraryUsageDescription"];
UIAlertController * alertController = [UIAlertController alertControllerWithTitle:accessDescription message:#"To give permissions tap on 'Change Settings' button" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancelAction];
UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:#"Change Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}];
[alertController addAction:settingsAction];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
}
}];
}
});
}
Also, there are some common cases when the alert doesn't appear. To avoid copying I would like you to take a look at this answer.
The first time the user tries to write to camera roll on ios 6 he/she is automatically asked for permission. You don't have to add extra code (before that the authorisationstatus is ALAuthorizationStatusNotDetermined ).
If the user denies the first time you cannot ask again (as far as I know). The user has to manually change that app specific setting in the settings->privacy-> photos section.
There is one other option and that is that it the user cannot give permission due other restrictions like parental control, in that case the status is ALAuthorizationStatusRestricted
Swift:
import AssetsLibrary
var status:ALAuthorizationStatus = ALAssetsLibrary.authorizationStatus()
if status != ALAuthorizationStatus.Authorized{
println("User has not given authorization for the camera roll")
}
#import <AssetsLibrary/AssetsLibrary.h>
//////
ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
switch (status) {
case ALAuthorizationStatusRestricted:
{
//Tell user access to the photos are restricted
}
break;
case ALAuthorizationStatusDenied:
{
// Tell user access has previously been denied
}
break;
case ALAuthorizationStatusNotDetermined:
case ALAuthorizationStatusAuthorized:
// Try to show image picker
myPicker = [[UIImagePickerController alloc] init];
myPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
myPicker.delegate = self;
[self presentViewController: myPicker animated:YES completion:NULL];
break;
default:
break;
}
iOS 9.2.1, Xcode 7.2.1, ARC enabled
'ALAuthorizationStatus' is deprecated: first deprecated in iOS 9.0 -
Use PHAuthorizationStatus in the Photos framework instead
Please see this post for an updated solution:
Determine if the access to photo library is set or not - PHPhotoLibrary (iOS 8)
Key notes:
Most likely you are designing for iOS7.0+ as of todays date, because of this fact you will need to handle both ALAuthorizationStatus and PHAuthorizationStatus.
The easiest is to do...
if ([PHPhotoLibrary class])
{
//Use the Photos framework
}
else
{
//Use the Asset Library framework
}
You will need to decide which media collection you want to use as your source, this is dictated by the device that your app. will run on and which version of OS it is using.
You might want to direct the user to settings if the authorization is denied by user.

Authenticating the local player - Game Center - iOS6

I'm completely new to development in Game Center. I have watched the videos in WWDC and looked at the developer website. They suggest I enter code like this for iOS 6:
- (void) authenticateLocalPlayer
{
GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error){
if (viewController != nil)
{
[self showAuthenticationDialogWhenReasonable: viewController
}
else if (localPlayer.isAuthenticated)
{
[self authenticatedPlayer: localPlayer];
}
else
{
[self disableGameCenter];
}
}];
}
I have copied this into the app delegate.m file, however it does not like it, showing errors like expecting a ] after [self showAuthenticationDialogWhenReasonable: viewController
} amongst others.
Can anyone please tell me how to authenticate the user for game center in iOS 6?
To get an introduction to GameKit, there are samples available from apple, for example:
https://developer.apple.com/library/ios/#samplecode/GKLeaderboards/Introduction/Intro.html.
In your code you are missing the closing "]", but of course you need more than just this function to connect to the gameCenter. Best start with one of the samples.
Apple has posted incorrect code, the ]; towards the end of the code belongs at the end of this line [self showAuthenticationDialogWhenReasonable: viewController
this code is not needed because this is just explaining how the method authenticateLocalPlayer works inside of Gamekit
Here's what I did without having to use the deprecated methods:
Set the authentication handler immediately in the AppDelegate by calling the function below (I put it in a singleton helper object). At this time, there is no view controller from which to show the login view controller, so if authentication fails, and the handler gives you a view controller, just save it away. This is the case when the user is not logged in.
- (void)authenticateLocalUserNoViewController {
NSLog(#"Trying to authenticate local user . . .");
GKLocalPlayer *_localPlayer = [GKLocalPlayer localPlayer];
__weak GKLocalPlayer *localPlayer = _localPlayer; // Avoid retain cycle inside block
__weak GCHelper *weakself = self;
self.authenticationViewController = nil;
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error)
{
if (viewController) {
NSLog(#"User not logged in");
weakself.authenticationViewController = viewController; // save it away
} else if (localPlayer.authenticated) {
[[GKLocalPlayer localPlayer] unregisterListener:self];
[[GKLocalPlayer localPlayer] registerListener:self];
NSLog(#"Local player %# (%#) authenticated. ID = %#",localPlayer.alias, localPlayer.displayName, localPlayer.playerID);
} else {
// Probably user cancelled the login dialog
NSLog(#"Problem authenticating %#", [error localizedDescription]);
}
};
}
Then, once your main screen has loaded, and the user wants to press a button the start an online game, present the login view controller that you stashed away earlier. I put this in another method in my helper class. When the user logs in, it will trigger an execution of your original authentication block, but the viewcontroller parameter will be nil.
-(BOOL) showGameCenterLoginController:(UIViewController *)presentingViewController {
if (self.authenticationViewController) {
[presentingViewController presentViewController:self.authenticationViewController animated:YES completion:^{
}];
return YES;
} else {
NSLog(#"Can't show game center view controller!");
return NO; // Show some other error dialog like "Game Center not available"
}
}

iOS:View controller crashes when trying to use camera in an application.

I have a button where when the user presses it, he is navigated to camera to take a pic.
When he takes the pic, he presses done and gets back to the controller. But when that happens the navigation bar gets up in the screen, gets below the battery/signal bar that the telephone has. The weird thing is that this happens on 4/4s but not on 3gs
It is rather tough to answer the question without knowing a bit more details, but here's some code I use to bring up the camera, take the picture, then close the camera successfully. The method can be called by using one line of code: [self takePhoto];
- (void) takePhoto {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//Clear out the UI first
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; -> use this if you want them to select from the library
[self presentViewController:picker animated:YES completion:nil];
} else {
//Device does not support a camera, show a message if desired
}
}
Then you need a delegate for it all so the program knows what to do when an image is taken or selected and how to close, that's what this code is:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
self.workingImage = nil;
//I grab the image and store globally, but first I manually scale and rotate it if necessary
self.workingImage = [self scaleAndRotateImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
//I display the image in my UI view, so this chunk of code will size it properly
CGRect bound;
bound.origin = CGPointZero;
bound.size = img.size;
imageView.bounds = bound;
//Set the UI image view and dismiss the controller
[imageView setImage:self.workingImage];
[picker dismissModalViewControllerAnimated:YES];
}
Obviously, make sure your controller .h implements the delegate properly like so:
#interface ViewController : UIViewController<UIImagePickerControllerDelegate> { ... }
Hope this helps?

UIImagePickerController won't record a video

I want to record a video with UIImagePickerController. My Problem is that the method [imagePickerController startVideoCapture]; always returns 0. I am testing the application with an iPhone 4S running iOS 5.1. Could somebody please help me with this:
- (IBAction)playButtonPushed:(id)sender
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIView *videoView = self.videoViewController.view;
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] >init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePickerController.mediaTypes = [[NSArray alloc] initWithObjects: (NSString >*)kUTTypeMovie, nil];
imagePickerController.showsCameraControls = NO;
imagePickerController.toolbarHidden = NO;
imagePickerController.wantsFullScreenLayout = YES;
imagePickerController.allowsEditing = YES;
imagePickerController.videoQuality = UIImagePickerControllerQualityTypeMedium;
imagePickerController.videoMaximumDuration = 30;
[imagePickerController startVideoCapture];
imagePickerController.cameraViewTransform = > CGAffineTransformScale(self.imagePickerViewController.cameraViewTransform, CAMERA_TRANSFORM, CAMERA_TRANSFORM);
imagePickerController.delegate = self;
[self.imagePickerViewController setCameraOverlayView:videoView];
NSLog(#"%s videoCapture: %d", __PRETTY_FUNCTION__, [imagePickerController > startVideoCapture]
);
[self presentModalViewController:imagePickerViewController animated:YES];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSLog(#"didFinishPickingMediaWithInfo");
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
NSLog(#"Cancel");
}
I had the same problem and Apple's documentation didn't help. That's because they missed to mention that startVideoCapture() can return false if you haven't set the capture mode to .video like this:
picker.cameraCaptureMode = .video
This worked for me and I'm able to capture videos now.
If im not mistaken, the "startVideoCapture" method is a bool
Taken straight from apple documentation:
startVideoCapture
Starts video capture using the camera specified by the UIImagePickerControllerCameraDevice property.
- (BOOL)startVideoCapture
Return Value
YES on success or NO on failure. This method may return a value of NO for various reasons, among them the following:
Movie capture is already in progress
The device does not support movie capture
The device is out of disk space
Discussion
Use this method in conjunction with a custom overlay view to initiate the programmatic capture of a movie. You can take more than one movie without leaving the interface, but to do so requires you to hide the default image picker controls.
Calling this method while a movie is being captured has no effect. You must call the stopVideoCapture method, and then wait until the associated delegate object receives an imagePickerController:didFinishPickingMediaWithInfo: message, before you can capture another movie.
Calling this method when the source type of the image picker is set to a value other than UIImagePickerControllerSourceTypeCamera results in the throwing of an NSInvalidArgumentException exception.
If you require additional options or more control over movie capture, use the movie capture methods in the AV Foundation framework. Refer to AV Foundation Framework Reference.
Availability
Available in iOS 4.0 and later.
Declared In
UIImagePickerController.h
stopVideoCapture
Stops video capture.
- (void)stopVideoCapture
Discussion
After you call this method to stop video capture, the system calls the image picker delegate’s imagePickerController:didFinishPickingMediaWithInfo: method.
Availability
Available in iOS 4.0 and later.
Declared In
UIImagePickerController.h
Think you need to call the startVideoCapture method after calling presentModalViewController:animated: and not before.
You probably also need a short delay (<1s?) after the UIImagePickerController has been presented on-screen and the animation has stopped, then call startVideoCapture, otherwise there are times where it will not start recording.
I had exactly the same problem. AndyV has it right, the recording won't start until the picker has been presented. I spent a lot of time trying to introduce a delay with sleep, but the simplest solution is to start a timer after displaying the picker using
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:#selector(startRecording) userInfo:nil repeats: NO];
Then ..
- (void)startRecording
{
BOOL result = [picker startVideoCapture];
}