IOS登陆获取IP地址Demo

作者: 星辰_入海 | 来源:发表于2019-04-12 23:10 被阅读164次

    翻看简书,上一次的简书文章还是上一周所更新的,小编在这一个星期将之前所讲述到的技术集合应用在了同一个应用本体上(小编为自己生日写的小程序),小编将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);
    }
    

    相关文章

      网友评论

        本文标题:IOS登陆获取IP地址Demo

        本文链接:https://www.haomeiwen.com/subject/ueqkwqtx.html