搜尋此網誌

2012年9月4日 星期二

在app中開啓設定(settings)的方法



[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General"]]
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General&path=Network"]]





This tutorial is about how to make your apps UX just a little bit better. Have you ever noticed the message in google maps stating that if you activate Wifi you would get a better positioning? Or that when you want to send a text message and your phone is on flight mode, that you get the message to de-activate flight mode in order to send a text?
Well, it is actually really simple. These are just links that are opened. So, in this tutorial I will show you how to do this using e.g. Reachability.

What you will learn

You will learn how to create a UIAlertView when no WIFI network is connected. The UIAlertView lets the user open the wifi settings directly from the app. You will also learn how to open other settings directly from your application.

What I expect from you

I expect you know how to use XCode and that you have some basic knowledge of Objective-C and development for iOS. A pro is if you have used UIAlertViews before.

What is required

Not more than a Mac with XCode 4.2+ installed

Good to know

I will be writing this for iOS 5 and be using ARC (Automatic Reference Counting), so you will not see any autoreleases, releases, deallocs ect.

So, lets start

First-off create a project called “AlertViewTest”. Make it a “Single View Application”. For the ease of this tutorial I chose only to support iPhone, so I recommend you do the same. However, this should work in a universal or iPad application as well.
So, now you will have your basic project. Nothing fancy, and nothing fancy needed.
Continue to next page …

Reachability

The next thing you need to do is to download a sample code from Apple. This sample code is called “Reachability” and is really usefull for your UX. You can download the code fromhttp://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html. But in case you do not have an paid subscription at Apple, you can also download it here: https://github.com/pokeb/asi-http-request/tree/master/External/Reachability
Download the file and unzip it (if downloaded from apple). Open the directory and drag the files “Reachability.m” and “Reachability.h” into XCode, just beneath the “AlertViewTest” group. Make sure you check the checkbox for “Copy items into destination group’s folder (if needed)”, see Pic.1.

Now your groups and files list should look like this (Pic.2)

Now, if you build your project you will notice a lot of build errors. This is due to several reasons; first-off you do not have the correct frameworks (yet) and second, the sample code is not written for the ARC standard. When using ARC, you are not allowed to allocate and release any objects. However, we can tell XCode not to expect ARC for these files. Lets start with that.
Left click on your project under “Project navigator”. The right side of xcode will change to the following (Pic.3)

Now, click “AlertViewTest” under targets, and then click “Build Phases”. You will see a new list of settings. Expand “Compile sources (4 items)” anddouble click on “Reachability.m”. Now a small window will popup with a textbox. In that text box write: “-fno-objc-arc” (without “) and press ENTER.
Since we are on that page anyways, expand “Link Binary With Libraries (3 items)”. Now click the + in the bottom left of that box. An new window will apprear. In this window, search for “SystemConfiguration.framework” and add it (Pic.4)

The contents of that page should now look like Pic.5.

Now you are all set; if you build your project now it should succeed. Lets start with some awesome coding.

Checking for WIFI connection

So, its time to write some code. Lets start with adding a function in our viewcontroller. Left click on “ViewController.h. Now add the following code beneath #import <UIKit/UIKit.h>:
1#import "Reachability.h"
and add the following code between @interface … and @end.
1- (void)checkForWIFIConnection;
Now left click on “ViewController.m” and add the following code just above @end.
01- (void)checkForWIFIConnection {
02 Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];
03NetworkStatus netStatus = [wifiReach currentReachabilityStatus];
04if (netStatus!=ReachableViaWiFi)
05 {
06 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"No WIFI available!", @"AlertView")
07 message:NSLocalizedString(@"You have no wifi connection available. Please connect to a WIFI network.", @"AlertView")
08 delegate:self
09 cancelButtonTitle:NSLocalizedString(@"Cancel", @"AlertView")
10 otherButtonTitles:NSLocalizedString(@"Open settings", @"AlertView"), nil];
11 [alertView show];
12 }
13 }
So, what does it do? Well, I am not going into every detail.. but basically what it does is that it askes the class Reachablitiy if there is a WIFI connection available. If there isn’t it will show an UIAlertView with a localized message. The message will offcourse be in english until you add translations.
But, if you run you application now, nothing will happen. What you also need to add is the following code in your “- (void) viewDidLoad” method:
1[self checkForWIFIConnection];
Your code for this page should now look like:
01#import "ViewController.h"
02
03@implementation ViewController
04
05- (void)didReceiveMemoryWarning
06{
07    [super didReceiveMemoryWarning];
08    // Release any cached data, images, etc that aren't in use.
09}
10
11#pragma mark - View lifecycle
12
13- (void)viewDidLoad
14{
15    [super viewDidLoad];
16    // Do any additional setup after loading the view, typically from a nib.
17
18    [self checkForWIFIConnection];
19}
20
21- (void)viewDidUnload
22{
23    [super viewDidUnload];
24    // Release any retained subviews of the main view.
25    // e.g. self.myOutlet = nil;
26}
27
28- (void)viewWillAppear:(BOOL)animated
29{
30    [super viewWillAppear:animated];
31}
32
33- (void)viewDidAppear:(BOOL)animated
34{
35    [super viewDidAppear:animated];
36}
37
38- (void)viewWillDisappear:(BOOL)animated
39{
40    [super viewWillDisappear:animated];
41}
42
43- (void)viewDidDisappear:(BOOL)animated
44{
45    [super viewDidDisappear:animated];
46}
47
48- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
49{
50    // Return YES for supported orientations
51    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
52}
53
54- (void)checkForWIFIConnection {
55    Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];
56
57    NetworkStatus netStatus = [wifiReach currentReachabilityStatus];
58
59    if (netStatus!=ReachableViaWiFi)
60    {
61        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"No WIFI available!", @"AlertView")
62                                                            message:NSLocalizedString(@"You have no wifi connection available. Please connect to a WIFI network.", @"AlertView")
63                                                           delegate:self
64                                                  cancelButtonTitle:NSLocalizedString(@"Cancel", @"AlertView")
65                                                  otherButtonTitles:NSLocalizedString(@"Open settings", @"AlertView"), nil];
66        [alertView show];
67    }
68}
69
70@end
Now, run your application and you will see the following (Pic.6):

Nice! Wouldn’t you say? No… not really since the buttons don’t do anything.. yet.
Now we need to implement the delegate function. Left click on your “ViewController.h” and add the following code directly after “@interface ViewController : UIViewController”
1<UIAlertViewDelegate>
Your ViewController.h file should now look like:
1#import <UIKit/UIKit.h>
2#import "Reachability.h"
3
4@interface ViewController : UIViewController <UIAlertViewDelegate>
5
6- (void)checkForWIFIConnection;
7
8@end
Now, left click on ViewController.m again and add the following code just above @end:
1- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
2{
3    if (buttonIndex == 1)
4    {
5        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];
6    }
7}
So what does this do then? Well, this is a delegate function from UIAlertView. When the UIAlertView did dismiss (someone pressed a button) we know which button has been pressed. Since “Cancel” has index 0 (first button) and our first real button we added as the show settings button, we just need to check if the buttonIndex is 1. If so, we tell the application to open an URL. However, the URL is a URLScheme. This means that when launcing this URL it will do something else then open safari.
There are a numerous type of URLSchemes, and you can even create your own (more on that some other time).
So, if you run your application now, you will open the wifi settings page in the settings app. However, the simulator does not support this so it will just open the front page of the settings app.

What else can you open?

Well, basicly anything. There is a great site listing many URLSchemes, and on this page of it you can find any page you can open:http://handleopenurl.com/scheme/apple-settings-app
So, I hope you enjoyed the tutorial. If so, please Facebook like it(!!) and also, Please Flattr it(!).
You can download the source here: Download source ZIP file here
Best regards,
Paul Peelen

Attached Files:

15 Responses to “iOS 4 & iOS 5 tutorial: UIAlertView with link to WIFI or Settings app using Reachability and XCode 4.2”

沒有留言:

張貼留言