after iOS 9, I used to check if my app had connection with my server with the next part of code, and If there is no response, I asked user to activate wifi, etc.
Alert which show the dialog:
#pragma mark - SHOW ALERTVIEW FOR IOS 7 or less AND IOS 8
-(void) alertNoInternet:(NSString*)alertTitle withMessage:(NSString *)alertMessage{
NSString *alert3gButtonText = #"Mobile Data";
NSString *alertWifiButtonText = #"WIFI";
NSString *alertCancelButtonText = #"Cancel";
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO( NSFoundationVersionNumber_iOS_8_0 ) ) {
NSLog(#"SQA: iOS 8 dialog process");
/*id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
if([rootViewController isKindOfClass:[UINavigationController class]])
{
rootViewController = [((UINavigationController *)rootViewController).viewControllers objectAtIndex:0];
}*/
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
message:alertMessage
preferredStyle:UIAlertControllerStyleActionSheet];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *action3g = [UIAlertAction actionWithTitle:alert3gButtonText
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSURL *urlCellular = [NSURL URLWithString:#"prefs:root=General&path=USAGE/CELLULAR_USAGE"];
if([[UIApplication sharedApplication] canOpenURL:urlCellular]) {
[[UIApplication sharedApplication] openURL:urlCellular];
}
[alertController dismissViewControllerAnimated:YES completion:nil];
//home button press programmatically
UIApplication *app = [UIApplication sharedApplication];
[app performSelector:#selector(suspend)];
//wait 2 seconds while app is going background
[NSThread sleepForTimeInterval:2.0];
//exit app when app is in background
exit(0);
}];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionWifi = [UIAlertAction actionWithTitle:alertWifiButtonText
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSURL *urlWifi = [NSURL URLWithString:#"prefs:root=WIFI"];
if ([[UIApplication sharedApplication] canOpenURL:urlWifi]) {
[[UIApplication sharedApplication] openURL:urlWifi];
}
[alertController dismissViewControllerAnimated:YES completion:nil];
//home button press programmatically
UIApplication *app = [UIApplication sharedApplication];
[app performSelector:#selector(suspend)];
//wait 2 seconds while app is going background
[NSThread sleepForTimeInterval:2.0];
//exit app when app is in background
exit(0);
}];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:alertCancelButtonText
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action)
{
[alertController dismissViewControllerAnimated:YES completion:nil];
//home button press programmatically
UIApplication *app = [UIApplication sharedApplication];
[app performSelector:#selector(suspend)];
//wait 2 seconds while app is going background
[NSThread sleepForTimeInterval:2.0];
//exit app when app is in background
exit(0);
}];
//[alertController addAction:action3g];
[alertController addAction:actionWifi];
[alertController addAction:actionCancel];
[self presentViewController:alertController animated:YES completion:nil];
}
if (SYSTEM_VERSION_LESS_THAN(NSFoundationVersionNumber_iOS_7_0) ) {
NSLog(#"SQA: iOS 7 or less dialog process");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:alertCancelButtonText
otherButtonTitles:alertWifiButtonText, nil];
alertView.tag = TAG_ALERT_NOINTERNET;
[alertView show];
}
}
And this is the source code to check the connection:
- (void)checkInternet:(connection)block
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://www.tempdevserver.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"HEAD";
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
request.timeoutInterval = 10.0;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
block([(NSHTTPURLResponse *)response statusCode] == 200);
}];
}
Now, on iOS 9, dialog is always shown, and never let me pass from there.
What has changed?
Here is the perfect solution, might be helpful to you.
**in your Appdelegate.m File**
//Check Internet Plugin
#include<unistd.h>
#include<netdb.h>
/////
#pragma mark Check Internet connection
-(BOOL)checkInternetConnection {
char *hostname;
struct hostent *hostinfo;
hostname = "google.com";
hostinfo = gethostbyname (hostname);
if (hostinfo == NULL)
{
NSLog(#"-> no connection!\n");
return NO;
}
else{
NSLog(#"-> connection established!\n");
return YES;
}
}
Try above code, it is working fine and perfect.
Related
My question is similar to "How can I prevent iOS apps from resetting after changing Camera permissions?".
But I don't understand the answer very well .
I set the microphone permission by the code as follow:
-(BOOL)canRecord
{
__block BOOL bCanRecord = NO;
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
{
//prompt
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"setting permission" message:#"need microphone permission" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *settingAction = [UIAlertAction actionWithTitle:#"setting now" style:UIAlertActionStyleDefault handler:^(UIAlertAction * a){
// jump to setting
NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
if ([[[UIDevice currentDevice]systemVersion]floatValue]>10.0) {
[[UIApplication sharedApplication] openURL:url options:#{} completionHandler:nil];
} else {
[[UIApplication sharedApplication] openURL:url];
}
}
}];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"later" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:settingAction];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}else{
if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession performSelector:#selector(requestRecordPermission:) withObject:^(BOOL granted) {
if (granted) {
bCanRecord = YES;
} else {
bCanRecord = NO;
}
}];
// }
}
NSLog(#"bCanRecord %d",bCanRecord);
}
return bCanRecord;
}
then back to my app by clicking the return key in the status bar, my app will force a refresh and I will lose my place in the app.
I'm using an iPhone5 running IOS 9.3.3.
I'm trying to implement an app accessing the camera roll. Here is how I'm checking for permissions:
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status != PHAuthorizationStatusAuthorized) {
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]
options:#{}
completionHandler:nil];
}];
[alertController addAction:settingsAction];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController
animated:YES
completion:nil];
}
}
I also add it Settings.bundle:
But I haven't figure it out how can link the toggle switch to the permissions. Any of you knows how can I link the toggle switch to the camera roll permissions ?
I'll really appreciate your help.
You can try this code :
if (status == PHAuthorizationStatusNotDetermined) {
// Access has not been determined.
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {
// do something
}else {
// Access has been denied.
}
}];
}
Technology: Objective-C, xCode 7
#property (nonatomic, copy) NSString *notes;
#synthesize notes;
example.notes = #"Click <a href='http://www.google.com'>here</a>";
NSString *msg = [#"" stringByAppendingFormat:#"%#", myAnnotation.notes];
UIAlertController *alertViewController = [UIAlertController alertControllerWithTitle: #"Title of Alert Box" message: msg preferredStyle: UIAlertControllerStyleAlert];
[alertViewController addAction: [UIAlertAction actionWithTitle: #"Close" style: UIAlertActionStyleCancel handler: nil]];
[self presentViewController: alertViewController animated: YES completion: nil];
Trying to get a link to appear in the Alert Box, but having no luck. Just outputs as plain text.
Is this even possible? If so, using my example above, how would you implement it?
Just like this.
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Alert Title"
message:msg
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"GO"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSString *urlString = #"someurl.com";
NSURL *url = [NSURL URLWithString:urlString];
if (NSClassFromString(#"SFSafariViewController"))
{
SFSafariViewController *safariViewController = [[SFSafariViewController alloc]initWithURL:url];
safariViewController.delegate = self;
[self presentViewController:safariViewController animated:YES completion:nil];
}
else
{
if ([[UIApplication sharedApplication] canOpenURL:url])
{
[[UIApplication sharedApplication] openURL:url];
}
}
}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
I've added code for opening link in SFSafariController only for iOS 9. In iOS 8 devices, it will open with safari browser as SFSafariController does not exist in iOS 8. This is done because apple now considers it bad user experience to exit the app to go to external links. So you can either open links in a web view or Safari Controller.
Im developing APNS.
When I send APNS, provide url and move the url.
APNS was succeed but When The app was running, it couldn't receive notification on foreground.
However on the background, it's work. when it's on foreground
it just move to url without notification.
Could you help me..?
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
UIApplicationState state = [UIApplication sharedApplication].applicationState;
BOOL state_active = (state == UIApplicationStateActive);
dic_apns = [userInfo objectForKey:#"aps"];
// alert export
NSString * msg = [dic_apns objectForKey:#"alert"];
NSString * eventcode = [userInfo objectForKey:#"eventcode"];
[[NSUserDefaults standardUserDefaults] setValue :msg forKey:#"push_msg"];
[[NSUserDefaults standardUserDefaults] setValue :eventcode forKey:#"eventcode"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"APNS : msg=%# | eventcode=%#", msg , eventcode);
[self goto_link];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
-(void) goto_link{
NSString * eventcode = [[NSUserDefaults standardUserDefaults] valueForKey:#"eventcode"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#%#", _MAIN_URL, _PUSH_PARAM, eventcode]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
ViewController* main = (ViewController *) self.window.rootViewController;
if (!main.webview_sin )
{
NSLog(#"main.webView is nil!!!");
}
[main.webview_sin loadRequest:request];
}
when it's on foreground it just move to url without notification
This is the expected behaviour. Notifications aren't shown if your app is running.
You could instead use a UIAlertController to show the message to the user
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if (application.applicationState == UIApplicationStateActive)
{
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:#"Notification"
message:/* Get the message from APS */
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction
actionWithTitle:#"Dismiss"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
//Do Nothing
}];
[alertController addAction:cancelAction];
[/*pick an appropriate view controller */ presentViewController:alertController animated:YES completion:nil];
}
}
Some code was adapted from here
My app uses user location in the background, but sometimes, users don't allow the app to always collect GPS data. The app can handle foreground only locations, and I'd like to set that as a fallback.
Is there a graceful way, once an iOS user has declined my AuthorizedAlways request, to re-prompt the user to give AuthorizedWhenInUse permission ?
You can't force it, but you can:
1) know that user is declined permission
2) and show an alert asking: "Please, go to settings and enable it".
3) go to ios settings ([[UIApplication sharedApplication] openURL:[NSURL URLWithString: UIApplicationOpenSettingsURLString]];)
Something like this:
- (void)checkLocation
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (status == kCLAuthorizationStatusAuthorizedAlways){
NSLog(#"ok");
} else if(status == kCLAuthorizationStatusDenied ||
status == kCLAuthorizationStatusAuthorizedWhenInUse){
[self showRequestLocationMessage];
} else if(status == kCLAuthorizationStatusNotDetermined){
//request auth
}
}
- (void)showRequestLocationMessage
{
UIAlertAction *action = [UIAlertAction actionWithTitle:#"Settings"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * alertAction){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: UIApplicationOpenSettingsURLString]];
}];
NSString *title = #"Service Enable";
NSString *text = #"Please enable your location.. bla bla bla";
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:title
message:text
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:#"Cancel"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
[alertController dismissViewControllerAnimated:YES completion:nil];
}];
[alertController addAction:cancelAction];
[alertController addAction:action];
[self presentViewController:alertController animated:YES completion:nil];
}