AddressBook privacy settings not enforced - objective-c

I'm doing some working getting an app to line up with the new privacy settings in iOS 8. I've completed the requirements satisfactorily for camera access and now I'm taking a look at how this app access the address book. I'm new to working with address book APIs so these questions may have obvious answers.
As with camera access, I was thinking that access to contacts would behave similarly with respect to the status of the privacy settings granted to the app. The thing is, so far, no matter what the value of ABAuthorizationStatus is - kABAuthorizationStatusNotDetermined or kABAuthorizationStatusDenied - access is always allowed.
Also, when the status is kABAuthorizationStatusNotDetermined, the 'Okay/Don't Allow' dialog is never displayed to the user (I've erased the phone and resinstalled the app to confirm). Furthermore, the app never shows up under the privacy settings. I assume this is because the status is always kABAuthorizationStatusNotDetermined.
The code to initiate access to contacts is below. The controller is shown (read only) and contacts' information can be obtained. Delegate code not shown.
// Debug - Value is always denied or not determined.
ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
// Existing code since iOS 7 - always works despite status.
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
[self presentViewController:picker animated:YES completion:nil];
It's great that everything seems to be working but I'd like what, if anything, I'm doing wrong.
iPhone 6,
iOS 8.0.2,
Xcode 6
Thanks!

From what I've found (and I could be wrong) while dealing with updating a code base to correctly deal with the new privacy settings in iOS 8 is that such settings are not respected uniformly across features. For example, without changes to address privacy settings for locations, access to CLLocationManager won't work. Depending on the app, this may appear to the user as though nothing is happening or an error message may appear. However, if no such changes are made for address book privacy settings, access is always granted.
I figured out my error after stumbling upon some extremely helpful example code posted by Apple. Below is code I add/modified so that privacy settings are respected properly in the app I work on. When I find the link to the code example I will post it.
-(void) presentAddressBookPicker {
switch (ABAddressBookGetAuthorizationStatus()) {
case kABAuthorizationStatusAuthorized:
[self accessGrantedForAddressBook];
break;
case kABAuthorizationStatusNotDetermined:
[self requestAccessToAddressBook];
break;
case kABAuthorizationStatusRestricted:
case kABAuthorizationStatusDenied:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
message:#"Unable to access address book"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
}
break;
default:
// Unlikely but log it anyway.
DLog(#"Unknown address book status.");
break;
}
}
-(void) accessGrantedForAddressBook {
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
[self presentViewController:picker animated:YES completion:nil];
}
-(void) requestAccessToAddressBook {
__weak MyWebViewController* weakSelf = self;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (granted) {
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf accessGrantedForAddressBook];
});
}
CFRelease(addressBook);
});
}

Related

setInitialText not work with IOS 8.3 (facebook,social,SLComposeViewController)

The functionality of SLComposeViewController no longer works as expected with the newest Facebook iPhone app update as of April 24th. Any initial text specified is ignored, though the setInitialText method returns true as if it was successful. The dialog then always returns "Done" whether you hit "Done" or "Cancel". I realize this is an Apple call and I'm not even using the Facebook SDK, but I have verified that everything works perfectly with the previous version of the Facebook App installed but when you upgrade the Facebook app on your iPhone, this functionality no longer works as expected.
Note that the result of the completion handler now always returns "Done" - even when you hit "Cancel" and also, the setInitialText: does nothing now. Verified that the same code worked pre-the april 24th release.
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[controller setInitialText:#"hiiiiiii"];
[controller setCompletionHandler:^(SLComposeViewControllerResult result)
{
if (result == SLComposeViewControllerResultCancelled)
{
NSLog(#"The user cancelled.");
}
else if (result == SLComposeViewControllerResultDone)
{
NSLog(#"The user posted to Facebook");
}
}];
[self presentViewController:controller animated:YES completion:nil];
}
else
{
SCLAlertView *alert = [[SCLAlertView alloc] init];
[alert showWarning:self title:#"alert" subTitle:#"facebook not installed" closeButtonTitle:#"ok" duration:0.0f];
}
At the time of this post, FB's still not allowing to set initial text, even using FB SDK.
A way I implemented to bypass the issue is to copy the content to clipboard and show a dialog to notify users that they can paste the preset content.
setInitialText: is not working anymore because Facebook has recently changed its policy about prefilling, but addURL: is still working and may be useful.
SLComposeViewController *mySLComposerSheet = [[SLComposeViewController alloc] init];
mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
NSURL *url = [[NSURL alloc] initWithString:linkString];
[mySLComposerSheet addURL:url];
[self presentViewController:mySLComposerSheet animated:YES completion:nil];
[mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result) {
NSString *output;
switch (result) {
case SLComposeViewControllerResultCancelled:
NSLog(#"SLComposeViewControllerResultCancelled");
break;
case SLComposeViewControllerResultDone:
NSLog(#"SLComposeViewControllerResultDone");
break;
}
}];
This way I can prefill Facebook post composer with the URL to my App.
I hope it to be useful.

iOS facebook SDK: Login already authenticated

I have had the Facebook iOS SDK running in an app I've been working on for a few months. At this point I am mostly using the SDK for SSO purposes.
Since I have started using iOS 6.0 I have been seeing an issue where the "Login to use your FB account with MY_APP" modal is blocking my current view.
The odd thing is that the user is already authenticated and apparently authorized to use my app. This is proven by the fact that I can get the user's email address and such.
It is also important to note that if I click the "X" it will close and everything is fine (user is authenticated/authorized). If I login as it tells me, it shows the "MY_APP is already authorized" modal which I cannot click the "Okay" button but I can click the "X" which again drops me back into my view with the user authenticated and authorized.
Here you can see the it:
To authenticate I am calling the following method in the appdelegate:
[appDelegate openSessionWithAllowLoginUI:YES];
The following are the relevant FB methods in my appdelegate:
// FACEBOOK STUFF
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [NSArray arrayWithObjects: #"email", nil];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
[self sessionStateChanged:session state:status error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState)state
error:(NSError *)error {
// FBSample logic
// Any time the session is closed, we want to display the login controller (the user
// cannot use the application unless they are logged in to Facebook). When the session
// is opened successfully, hide the login controller and show the main UI.
switch (state) {
case FBSessionStateOpen: {
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
[self sendAuthenticationStatusChangedNotification];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// FBSample logic
// Once the user has logged in, we want them to be looking at the root view.
[FBSession.activeSession closeAndClearTokenInformation];
//[self showLoginView];
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
// FBSample logic
// We need to handle URLs by passing them to FBSession in order for SSO authentication
// to work.
return [FBSession.activeSession handleOpenURL:url];
}
EDIT 1
I noticed that this is happing on one of my phones but not the other. The phone that wasn't working had an older version of the FB app installed. Updating the FB app stopped this issue from happening. I am still interested in a fix to avoid others from experiencing the same issue.
EDIT 2
The issue went away for a little but now is back even with the new facebook app installed. Please help!
The problem for me actually turned out to be a silly one. I was calling
[appDelegate openSessionWithAllowLoginUI:YES];
two times due to a button click event that was wired up twice. As soon as it was only being called once, the issue went away!

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.

Strange error when dismissing MFMailComposeViewController: error: address doesn't contain a section that points to a section in a object file

I am getting a really weird error MFMailCompseViewController. The error is "error: address doesn't contain a section that points to a section in a object file". The app crashes after MFMailCompseViewController dismisses and the email actually get sent.
This is specific to MFMailComposeViewController as I have tried to present a plain view controller modally and it dismisses fine.
Here is the code I wrote to calland present mail composer:
- (void) emailImage:(UIImage *)img {
//verified that the image is being returned correctly
UIImage *img1 = [[_delegate photoBrowser:self photoAtIndex:0] underlyingImage];
MFMailComposeViewController *mfViewController = [[MFMailComposeViewController alloc] init];
mfViewController.mailComposeDelegate = self;
NSString *subject = #"Check out this photo I took - Cap That App";
[mfViewController setSubject:subject];
NSData *imgData = UIImageJPEGRepresentation(img1, 1.0);
[mfViewController addAttachmentData:imgData mimeType:#"image/jpg" fileName:#"photo.jpg"];
NSString *contactMessage = #"\n\nSent via Cap That - Available in the Apple App Store";
[mfViewController setMessageBody:contactMessage isHTML:YES];
[self presentViewController:mfViewController animated:YES completion:nil];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Status:" message:#"" delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil] autorelease];
switch (result) {
case MFMailComposeResultCancelled:
alert.message = #"You chose not to send the email.";
break;
case MFMailComposeResultSaved:
alert.message = #"Your email was saved as a draft. It has not been sent yet.";
break;
case MFMailComposeResultSent:
alert.message = #"Your email has been sent!";
break;
case MFMailComposeResultFailed:
alert.message = #"There was an error sending the email. Please verify your email is working and try again.";
break;
default:
alert.message = #"You chose not to send the email.";
break;
}
[self dismissViewControllerAnimated:YES completion:^(void) {
[alert show];
}];
}
Thanks in advance for anyone's help on this.
I'm getting the same error in my app, acting on a tap gesture on a HUD. My gesture recognizer method is using a block property on the HUD to perform the needful actions, and there's where it's crashing (the code within the block never gets to run). Apparently the program cannot access that code, and since you also have a completion block that might be a clue to what's happening.
I don't see that I'm doing anything wrong in my code, and you don't seem to be doing that either, so maybe it's a bug. Are you by any chance running a developer preview of Xcode (4.4 or 4.5)?
Edit: it turns out my problem was that the code block property was being released before it got the chance to run. I think a similar thing might happend in your case, with the alert var. Can you try moving the alert init within the completion block?
Edit 2: As an alternative, try prefixing the alert init with __weak (or __unsafe_unretained if you're targetting iOS 4.3), that should do it. If you're not using ARC, use __block instead.

Working with iOS Location Manager

I am developing an app that has many view. Into my app sometimes the user arrives to a view where he can ask for his position clicking over a button. I am trying to follow the Apple guide lines to only ask for the user position if the user allows to do it. What should I do, use the next first code into the app delegate and declare a location manager attribute into any view that the user invokes, passing the location manager attribute to the new view and from the old view and asking with the second next code anytime that the user clicks the button to locate himself?; or just use the second code, declaring a location manager attribute only into the views that allow to get the user location with a button, to check if the location services are enable?
First snippet.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Add the navigation controller's view to the window and display.
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
// Create a location manager instance to determine if location services are enabled. This manager instance will be
// immediately released afterwards.
CLLocationManager *manager = [[CLLocationManager alloc] init];
if (manager.locationServicesEnabled == NO) {
UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:#"Location Services Disabled" message:#"You currently have all location services for this device disabled. If you proceed, you will be asked to confirm whether location services should be reenabled." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[servicesDisabledAlert show];
[servicesDisabledAlert release];
}
[manager release];
return YES;
}
Second snippet.
- (IBAction)locateUser:(id)sender {
if([CLLocationManager locationServicesEnabled]) {
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
} else {
[[[[UIAlertView alloc] initWithTitle:#"Location services."
message:#"Location services are disabled."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease] show];
}
}
Thanks for reading.
CoreLocation will handle all the alerts for you. If locations services are disabled and that you ask for the location, CoreLocation will show an alert telling so to the user with a button to go directly to Settings.app.
If you want to know what append you can check for the delegate call
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
The error here contains a code that will be kCLErrorDenied if the user doesn't let the app use location services.
Also, you should use CoreLocation when the user need it. It's not necessary to check for location services at launch and the overhead of multiple CLLocationManager is almost inexistent.