IOS登陆获取IP地址Demo

翻看简书,上一次的简书文章还是上一周所更新的,小编在这一个星期将之前所讲述到的技术集合应用在了同一个应用本体上(小编为自己生日写的小程序),小编将Demo代码投放下文,如果有更好的建议或者不理解的地方欢迎留言讨论~


图1--程序首页

在此Demo中主要包括了一下内容

  • UITextField文本输入框的应用
  • 标签UILabel的使用
  • 按钮UIButton的使用,响应事件
  • 开关UISwitch空间的设置
  • 显示当前时间的NSTimer的使用
  • 警告框UIAlert以及UIAlertSheet的使用
  • 活动器的使用
  • webView的使用
  • 获取本机的IP地址(将在下一章详细讲述代码分析)

程序首要的思路

确定程序输入时候的Name and Password和之前预设的值相吻合时候,则当按下注销或者破解按钮进入WebView,当输入错误时候则退出应用程序(强行,非正常退出)

让小编带着大家通过代码和程序视图来一点一点分析这个Demo吧

1.首先,现在故事版中拖动响应的控件UILabel and UIButton and UITextField,并在接口处设置输出接口,并设置TextField的协议和网络协议

@interface ViewController () <UITextFieldDelegate,WKNavigationDelegate>
@property (weak, nonatomic) IBOutlet UILabel *ipOfLabel;
@property (weak, nonatomic) IBOutlet UILabel *ipAdressOfLable; //获取ip地址的标签
@property (weak, nonatomic) IBOutlet UILabel *localTimeSettingOfLabel; //获取本地时间的标签
@property (weak, nonatomic) IBOutlet UILabel *localTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *editorOfLabel;
@property (weak, nonatomic) IBOutlet UILabel *idOfLabel;
@property (weak, nonatomic) IBOutlet UILabel *passwordOfLabel; //密码
@property (weak, nonatomic) IBOutlet UILabel *nameOfLabel; //名字
@property (weak, nonatomic) IBOutlet UITextField *nameOfTextField; //名字输入框
@property (weak, nonatomic) IBOutlet UILabel *controllerOfLabel;
@property (weak, nonatomic) IBOutlet UITextField *passwordOfTextField; //密码输入框
@property (weak, nonatomic) IBOutlet UIButton *buttonToBack; //网页返回按钮
@property (weak, nonatomic) IBOutlet UITextField *idOfTextField;
@property (weak, nonatomic) IBOutlet UIButton *EnterButton; 
@property (weak, nonatomic) IBOutlet UISwitch *switchOfEdite; //开关控件
@property (weak, nonatomic) IBOutlet UISwitch *switchOfControl;
@property (nonatomic,strong) UIActivityIndicatorView *activeIndicatorView; //活动器视图
@property (nonatomic,strong) UILabel *webLabel;
@property (strong,nonatomic) WKWebView *webView; //网页视图
@end

2.开关控件的设置

目的:使得文本框可编辑或不可编辑,以及使得按钮隐藏以及显示
- (IBAction)controlOfSwitchToChangeTheButtonHiddedandShow:(UISwitch *)sender {
    //控制按钮显示状态
    if ([self.buttonToBack isHidden] || [self.EnterButton isHidden]) {
        [self.EnterButton setHidden:NO];
        [self.buttonToBack setHidden:NO];
    }else{
        [self.EnterButton setHidden:YES];
        [self.buttonToBack setHidden:YES];
    }
}

- (IBAction)editeOfSwitchToChangeTheTextFieldHiddedAndShow:(UISwitch *)sender {
    //控制文本框状态
    if ([self.nameOfTextField isEnabled] || [self.passwordOfTextField isEnabled] || [self.idOfTextField isEnabled]) {
        [self.nameOfTextField setEnabled:NO];
        [self.passwordOfTextField setEnabled:NO];
        [self.idOfTextField setEnabled:NO];
    }else{
        [self.nameOfTextField setEnabled:YES];
        [self.passwordOfTextField setEnabled:YES];
        [self.idOfTextField setEnabled:YES];
    }
}

图2--开关控制文本框

图3--开关控制按钮的显示

3.文本框输入

  • 文本框进行输入读取文本框的内容
  • 实现文本框的协议
- (IBAction)enterTheButtonToOpenTheWebView:(UIButton *)sender {
    //设置破解的情况
    if ([self.nameOfTextField.text isEqualToString:[NSString stringWithFormat:@"%@",@"ReynBryant"]]) {
        if ([self.passwordOfTextField.text isEqualToString:[NSString stringWithFormat:@"%@",@"19990414"]]) {
            //打开警告框
            NSLog(@"打开警告框");
            [self testAlertController];
        }
    }else{
        [self errorAlertView]; //错误输入
    }
}

- (IBAction)backTheButtonToOpenTheWebView:(UIButton *)sender {
    //设置注销的情况
    //设置破解的情况
    if ([self.nameOfTextField.text isEqualToString:[NSString stringWithFormat:@"%@",@"ReynBryant"]]) {
        if ([self.passwordOfTextField.text isEqualToString:[NSString stringWithFormat:@"%@",@"19990414"]]) {
            //打开警告框
            NSLog(@"打开警告框");
            [self setAlertController];
        }
    }else{
        [self errorAlertView];
    }
}
图4--警告框的显示

图5--警告显示
#pragma mark -- TextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    NSLog(@"the textField did and editing.");
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    NSLog(@"the textField did begin editing.");
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSLog(@"return");
    //关闭键盘
    [self.nameOfTextField resignFirstResponder];
    [self.idOfTextField resignFirstResponder];
    [self.passwordOfTextField resignFirstResponder];
    return YES;
}
关闭键盘后,要监听键盘的变化,所以我们需要加入通知机制,同时还实现了对于手机退出软件以及锁屏时候的监听
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidshow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(iphoneClose) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheMemory) name:UIApplicationWillResignActiveNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidshow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(iphoneClose) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheMemory) name:UIApplicationWillResignActiveNotification object:nil];
}

- (void)changeTheMemory{
    NSLog(@"Locked");
    [self didReceiveMemoryWarning];
}

- (void)iphoneClose{
    NSLog(@"Did receiveMemoryWarningNotification.");
}
- (void)keyboardDidshow:(id)sender{
    NSLog(@"键盘打开");
}
- (void)keyboardDidHide:(id)sender{
    NSLog(@"键盘关闭");
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

4.当信息匹配成功后点击按钮的一瞬间弹出警告框的设置

- (void)testAlertController{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"UNCLOCK" message:@"Are you want to unlock it" preferredStyle:(UIAlertControllerStyleAlert)];
    //UIAlertController *alertController = [[UIAlertController alloc] init];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Tap the CancelButton");
        UIAlertController *alertController = [[UIAlertController alloc] init];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"YES");
        }];
        UIAlertAction *backAction = [UIAlertAction actionWithTitle:@"Turn Back" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"NO");
            exit(EXIT_FAILURE);
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:backAction];
        [self presentViewController:alertController animated:TRUE completion:nil];
    }];
    UIAlertAction *enterAction = [UIAlertAction actionWithTitle:@"Enter" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Tap the EnterButton");
        [self setWebView];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:enterAction];

    //显示
    [self presentViewController:alertController animated:TRUE completion:nil];
}

5.当输入错误时候,或者注销时候的警告框如下

- (void)setAlertController{
    UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"CLOSE" message:@"CLOSE THE WINDOW" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"Enter" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"enter the yesAction");
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
        backButton.frame = CGRectMake(0, UIScreen.mainScreen.bounds.size.height-20, 90, 23);
        [backButton setTitle:@"Back" forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(overtheWebView:) forControlEvents:(UIControlEventTouchUpInside)];
        self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height)];
        self.webView.backgroundColor = [UIColor blackColor];
        NSString *urlStr = @"http://hackcode.ishoulu.com/swan/";
        NSURL *url = [NSURL URLWithString:urlStr];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [self.webView loadRequest:request];
        self.webView.navigationDelegate = self;
        [self.webView addSubview:backButton];
        [self.view addSubview:self.webView];
    }];
    
    [alerController addAction:yesAction];
    [self presentViewController:alerController animated:TRUE completion:nil];
}


- (void)errorAlertView{
    UIAlertController *errorAlertController = [UIAlertController alertControllerWithTitle:@"Error" message:@"Your name and password is error" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        exit(EXIT_FAILURE);
    }];
    [errorAlertController addAction:okAction];
    [self presentViewController:errorAlertController animated:TRUE completion:nil];
}

图6--错误警告框的弹出

6.载入网页

- (void)setWebView{
    //位置
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height)];
    self.webView.backgroundColor = [UIColor blackColor];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(UIScreen.mainScreen.bounds.size.width/2-20, UIScreen.mainScreen.bounds.size.height-20, 90, 23);
    [backButton setTitle:@"Back" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(overtheWebView:) forControlEvents:(UIControlEventTouchUpInside)];
    //self.webView.backgroundColor = [UIColor blackColor];
    [self setURL];
    [self.webView addSubview:backButton];
    [self.view addSubview:self.webView];
}

- (void)overtheWebView:(id)sender{
    [self.webView removeFromSuperview];
}

- (void)setURL{
    NSString *urlStr = @"http://astro.sina.com.cn/feeling/Aries.html";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    self.webView.navigationDelegate = self;
}
图7--网页视图的导入
#pragma mark -- URLDelegate
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    NSLog(@"the webView did commit.");
    [self.activeIndicatorView removeFromSuperview];
    [self.webLabel removeFromSuperview];
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"the webView finish.");
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"the webView start.");
    //添加状态显示
    self.activeIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhiteLarge)];
    self.activeIndicatorView.frame = CGRectMake(UIScreen.mainScreen.bounds.size.width/2-20, UIScreen.mainScreen.bounds.size.height/2-30, 50, 20);
    self.activeIndicatorView.hidesWhenStopped = false;
    [self.activeIndicatorView startAnimating];
    //添加标签
    self.webLabel = [[UILabel alloc] initWithFrame:CGRectMake(UIScreen.mainScreen.bounds.size.width/2-100, UIScreen.mainScreen.bounds.size.height/2, 220, 20)];
    self.webLabel.text = @"Welecome To The System";
    self.webLabel.textAlignment = NSTextAlignmentCenter;
    self.webLabel.textColor = [UIColor whiteColor];
    [self.webView addSubview:self.webLabel];
    [self.webView addSubview:self.activeIndicatorView];
    
    //网页处理方式
    self.webView.allowsBackForwardNavigationGestures = YES;
    [self.webView configuration];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"error");
    exit(EXIT_FAILURE);
}

7.对于提前要预加载在软件界面的东西我们通常放置在ViewdidLoad中加载

#pragma mark -- viewSetting
- (void)viewDidLoad {
    [super viewDidLoad];
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:UIScreen.mainScreen.bounds];
    imageView.image=[UIImage imageNamed:@"Image"];
    [self.view insertSubview:imageView atIndex:0];
    [self.switchOfControl setOn:YES];
    //显示当地时间标签
    NSDate *theDate = [[NSDate alloc] init];
    NSString *localTimeStr = [theDate descriptionWithLocale:[NSLocale autoupdatingCurrentLocale]];
    NSLog(@"%@",localTimeStr);
    self.localTimeSettingOfLabel.text = [NSString stringWithString: localTimeStr];
    //键盘的方式
    self.passwordOfTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    self.idOfTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    //ip
    self.ipAdressOfLable.text = [self getIPAddress];
}

此上就是这项Demo最基础的部分,其概念以及具体的实现也在前文有所提及,若上不熟悉可以查看之前的文章,有所讲解,接下来的代码是本个程序的核心所在,获取IP地址的方法,在小编极力搜索下,最终,找到了一下代码,并亲测是有效的,本次文章尚不讲解原理,下一篇文章会详细的讲述代码的工作原理,本次只是将代码呈现出来,具体内容,下一篇讲解

//Get IP Address
- (NSString *)getIPAddress{
    NSString *adress = @"error"; //先设置了一个字符串地址为error,当未插卡时候则返回为error
//    struct ifaddrs {
//        struct ifaddrs  *ifa_next;
//        char        *ifa_name;
//        unsigned int     ifa_flags;
//        struct sockaddr    *ifa_addr;
//        struct sockaddr    *ifa_netmask;
//        struct sockaddr    *ifa_dstaddr;
//        void        *ifa_data;
//    };
    struct ifaddrs *interfaces = NULL; //设置ifaddrs接口结构体为空
    struct ifaddrs *temp_addr = NULL; //临时地址变量为空
    int success = 0; //当成功时候为0
    //retrieve the current interface - return 0 on success
//#include <sys/cdefs.h>
//
//    __BEGIN_DECLS
//    extern int getifaddrs(struct ifaddrs **);
//    extern void freeifaddrs(struct ifaddrs *);
//    extern int getifmaddrs(struct ifmaddrs **) API_AVAILABLE(macos(10.7), ios(4.3), watchos(4.0), tvos(11.0));
//    extern void freeifmaddrs(struct ifmaddrs *) API_AVAILABLE(macos(10.7), ios(4.3), watchos(4.0), tvos(11.0));
//    __END_DECLS
//
//#endif
    success = getifaddrs(&interfaces); //全局变量获得地址 将定义的结构体的interfaces地址传给struct ifaddrs **
    if (success == 0) {
        //if success is zero --> if
        //Loop througt linked of interfaces
        temp_addr = interfaces; //将结构体复制给副本temp_addr
        while (temp_addr != NULL) {
            //temp_addr是一个结构指针
            //struct sockaddr {
//            __uint8_t    sa_len;        /* total length */
//            sa_family_t    sa_family;    /* [XSI] address family */
//            char        sa_data[14];    /* [XSI] addr value (actually larger) */
//        };
            //#define    AF_INET        2        /* internetwork: UDP, TCP, etc. */
            if (temp_addr->ifa_addr->sa_family == AF_INET) {
                //check if interface is en0 which is the wifi conection on the iphone
                if ([[NSString stringWithUTF8String:temp_addr ->ifa_name] isEqualToString:@"en0"]) {
                    //char        *inet_ntoa(struct in_addr);
                    //inet_ntoa --> 字符串指针函数(形参是结构体)
                    //struct in_addr {
//                    in_addr_t s_addr;
//                };
                    adress = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
//                    struct sockaddr_in {
//                        __uint8_t    sin_len;
//                        sa_family_t    sin_family;
//                        in_port_t    sin_port;
//                        struct    in_addr sin_addr;
//                        char        sin_zero[8];
//                    };
                }
            }
            temp_addr = temp_addr -> ifa_next;
        }
    }
    
    //Free memory
//    extern void freeifaddrs(struct ifaddrs *);
    freeifaddrs(interfaces);
    return (adress);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容