Learning Summary of iOS Basic Course-Network Operation

Keywords: iOS network Session Mobile encoding

Time: Tuesday, 23 May 2017
Note: Part of the content of this article is from Mucho.com. @ Mu Course Net: http://www.imooc.com
Teaching sample source code: none
Personal learning source code: https://github.com/zccodere/s...

Chapter 1: Learning Guide

1-1 Learning Guide

Learning content

Introduction to HTTP
 HTTP effect
 Get a piece of network data: get request
 Update a piece of network data: post request
 Loading Web pages with UIWebView
 summary

Origin of HTTP


Introduction to HTTP

HyperText Transfer Protocol, Hypertext Transfer Protocol
 Text, picture, voice, video

Use scenarios

Opening Baidu Page is a web request about HTTP
 The login operation on mobile App is a network request about HTTP
 Picture download is a web request about HTTP

HTTP roles

Chapter 2: Network Analysis

2-1 Network Request Resolution

HTTP effect

HTTP is a protocol for information communication between client and server.
The URL decides who to communicate with.

URL structure

What is communication?

How to communicate?

Multiple clients access the same server in different ways
 HTTP provides a standard and specification for communication between client and server.

Common request methods

Network Request in iOS

NSURL: Used to indicate which server specified resource the client accesses
 NSURLRequest: Used to represent the content of a network request initiated by a client
 NSURLConnection: Used to represent a network connection between a client and a server [outdated]
NSURLResponse: Used to represent the result of the server's response to the client's request

2-2 Sends the First Network Request

The impact of multiple security incidents

Exposure of Apple's "Xcode Ghost" Incident
 Brilliant Exposure of Several Celebrities
 New App Transport Security (ATS) feature in iOS 9
 Enforcing HTTPS to Improve Security Level

In order to facilitate version iteration, a key value is provided to set up and use HTTP normally. Add the following configuration to the Info.plist file.

Code demonstration:

1. Configuration allows http requests

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

2.http request code

// The NSURLConnection class is out of date, using the alternative class NSURLSession
    
// Servers representing access
NSURL *url = [NSURL URLWithString:@"http://www.imooc.com"];

// Represents the request content of a network request initiated by a client
//NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

request.HTTPMethod = @"GET";

// Get the session object
NSURLSession *session = [NSURLSession sharedSession];

// Create a Task task based on the session object
NSURLSessionTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response, NSError * _Nullable error){
    
    // Analytical response data
    NSLog(@"Getting data from the server,Response message:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

}];

// Execution of tasks
[sessionDataTask resume];

Chapter 3: Sending requests by Get

3-1 Building User Information Interface

Obtaining network data

Get personal user information from the network, parse the data and display it on the page

Getting Information Interface Documents

Request address: http://127.0.0.1:12580/WebServer/docPath
 Request mode: GET
 Request parameters:
    Does the parameter name type have to be specified
    userId int yes
 Response parameters:
    Description of parameter name type
    bstatus jsonObj response result message
    bstatus.code int status code
    bstatuc.des String State Description
    userInfo jsonObj user information
    userInfo.userName String username
    userInfo.userSex int Gender: 0,, Male; 1, Female
    Birthday of userInfo.birthday String, "05-23"
    userInfo.email String, 2539943892@qq.com
    userInfo.phone String mobile number, 135****** 8142

Functional prototype diagram

Code demonstration:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // Set the parent View background color
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    // Create Title Control
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, kScreenWidth, 20)];
    [titleLabel setText:@"Personal User Information"];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:18];
    titleLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:titleLabel];
    
    // Create username controls
    _userNameView = [[KeyValueView alloc] initWithFrame:CGRectMake(100, 70, kScreenWidth - 100 *2 , 30)];
    _userNameView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_userNameView];
    
    // Creating User Gender Controls
    _userSexView = [[KeyValueView alloc] initWithFrame:CGRectMake(100, 70 + 30, kScreenWidth - 100 *2 , 30)];
    _userSexView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_userSexView];
    
    // Create User Birthday Control
    _userBirthdayView = [[KeyValueView alloc] initWithFrame:CGRectMake(100, 70 + 30 * 2, kScreenWidth - 100 *2 , 30)];
    _userBirthdayView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_userBirthdayView];
    
    // Create User Mailbox Control
    _userEmailView = [[KeyValueView alloc] initWithFrame:CGRectMake(100, 70 + 30 * 3, kScreenWidth - 100 *2 , 30)];
    _userEmailView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_userEmailView];
    
    // Creating User Mobile Controls
//    _userPhoneView = [[KeyValueView alloc] initWithFrame:CGRectMake(100, 70 + 30 * 4, kScreenWidth - 100 *2 , 30)];
//    _userPhoneView.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:_userPhoneView];
    
    _phoneLable = [[UILabel alloc] initWithFrame:CGRectMake(100, 70 + 30 * 4, (kScreenWidth -100*2)/3, 30)];
    _phoneLable.backgroundColor = [UIColor clearColor];
    _phoneLable.textAlignment = NSTextAlignmentLeft;
    _phoneLable.font = [UIFont systemFontOfSize:16];
    _phoneLable.textColor = [UIColor blackColor];
    [self.view addSubview:_phoneLable];
    
    // Create Editable User Mobile Number Control
    _phoneTextFiled = [[UITextField alloc] initWithFrame:CGRectMake(100+(kScreenWidth -100*2)/3, 70 + 30 * 4, kScreenWidth - 100 *2, 30)];
    _phoneTextFiled.backgroundColor = [UIColor clearColor];
    _phoneTextFiled.textAlignment = NSTextAlignmentLeft;
    _phoneTextFiled.font = [UIFont systemFontOfSize:16];
    _phoneTextFiled.textColor = [UIColor blackColor];
    // Setting Keyboard Format Digital Keyboard
    _phoneTextFiled.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:_phoneTextFiled];
    
    // Request button control
    UIButton *getUserInfoButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 70 + 30 * 5, kScreenWidth - 100*2, 30)];
    getUserInfoButton.backgroundColor = [UIColor redColor];
    [getUserInfoButton setTitle:@"pick up information" forState:UIControlStateNormal];
    [getUserInfoButton setTintColor:[UIColor whiteColor]];
    // Adding Events
    [getUserInfoButton addTarget:self action:@selector(loadGetWebRequest:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:getUserInfoButton];
    
    // Save button control
    UIButton *saveUserInfoButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 70 + 30 * 7, kScreenWidth - 100*2, 30)];
    saveUserInfoButton.backgroundColor = [UIColor redColor];
    [saveUserInfoButton setTitle:@"Save information" forState:UIControlStateNormal];
    [saveUserInfoButton setTintColor:[UIColor whiteColor]];
    // Adding Events
    [saveUserInfoButton addTarget:self action:@selector(loadPostWebRequest:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveUserInfoButton];
    
    
}

3-2 Initiate Network Request to Get Data

Code demonstration:

// Launching GET requests and parsing response data
-(void)loadGetWebRequest:(id)sender{
    // Specify the server address to be accessed
    NSURL *url = [NSURL URLWithString:@"http://115.159.205.199:12580/WebServer/user/1"];
    // Creating the request object NSURLRequest defaults to GET
    //NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // Setting Request Mode
    [request setHTTPMethod:@"GET"];
    
    // Get the session object
    NSURLSession *session = [NSURLSession sharedSession];
    // Create a Task task based on the session object
    NSURLSessionTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response, NSError * _Nullable error){
        
        // Analytical response data
        //NSLog(@ "Get data from the server, response message:%@", [[NSString alloc] initWithData: data encoding: NSUTF8 String Encoding]);
        
        // Parsing JOSN data
        id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        //NSLog(@ "Get data from the server, response message:%@", obj);
        // If obj is a dictionary type
        if([obj isKindOfClass:[NSDictionary class]]){
            NSDictionary *userInfo = [(NSDictionary *)obj objectForKey:@"userInfo"];
            
            NSString *userName = [userInfo objectForKey:@"userName"];
            [_userNameView setupKey:@"Full name" value:userName];
            NSLog(@"userName = %@",userName);
            
            NSString *userSex = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"userSex"]];
            if([userSex isEqualToString: @"1"]){
                userSex = @"female";
            }
            if([userSex isEqualToString: @"0"]){
                userSex = @"male";
            }
            [_userSexView setupKey:@"Gender" value:userSex];
            NSLog(@"userSex = %@",userSex);
            
            NSString *userBirthday = [userInfo objectForKey:@"userBirthday"];
            [_userBirthdayView setupKey:@"Birthday" value:userBirthday];
            NSLog(@"userBirthday = %@",userBirthday);
            
            
            NSString *userEmail = [userInfo objectForKey:@"userEmail"];
            [_userEmailView setupKey:@"mailbox" value:userEmail];
            NSLog(@"userEmail = %@",userEmail);
            
            NSString *userPhone = [userInfo objectForKey:@"userPhone"];
//            [_userPhoneView setupKey:@ "Mobile phone" value:userPhone];
            [_phoneLable setText:@"Mobile phone"];
            [_phoneTextFiled setText:userPhone];
            NSLog(@"userPhone = %@",userPhone);
            
            
        }
        
    }];
    
    // Execution of tasks
    [sessionDataTask resume];
}

Chapter 4: Sending requests by Post

4-1 Editing User Information

Functional Page Prototype

Modifying Information Interface Documents

Request address: http://127.0.0.1:12580/WebServer/docPath
 Request mode: POST
 Request parameters:
    Does the parameter name type have to be specified
    userId int yes
    phone String no
    email String no
 Response parameters:
    Description of parameter name type
    bstatus jsonObj response result message
    bstatus.code int status code
    bstatuc.des String State Description

4-2 Use Post Request to Modify Data

Code demonstration:

// Initiate POST requests and parse response data
-(void)loadPostWebRequest:(id)sender{
    
    // There is no need to splice network request parameters behind URLs
    NSURL *url = [NSURL URLWithString:@"http://115.159.205.199:12580/WebServer/user/1"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    
    // Edited mobile phone number
    NSString *newPhone = [_phoneTextFiled text];
    
    // Encapsulation request parameters
    NSString *postParam = [NSString stringWithFormat:@"phone=%@",newPhone];
    NSData *postData = [postParam dataUsingEncoding:NSUTF8StringEncoding];
    // POST request parameters are assigned using the following methods
    [request setHTTPBody:postData];
    
    // Get the session object
    NSURLSession *session = [NSURLSession sharedSession];
    // Create a Task task based on the session object
    NSURLSessionTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response, NSError * _Nullable error){
        
        // Analytical response data
        //NSLog(@ "Get data from the server, response message:%@", [[NSString alloc] initWithData: data encoding: NSUTF8 String Encoding]);
        
        // Parsing JOSN data
        id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        //NSLog(@ "Get data from the server, response message:%@", obj);
        // If obj is a dictionary type
        if([obj isKindOfClass:[NSDictionary class]]){
            NSDictionary *bstatus = [(NSDictionary *)obj objectForKey:@"bstatus"];
            
            NSString *desc = [bstatus objectForKey:@"desc"];
            [_userNameView setupKey:@"describe" value:desc];
            NSLog(@"desc = %@",desc);
            
        }
    }];
    
    // Execution of tasks
    [sessionDataTask resume];

}

4-3 Network Request Status Code

The difference between Get and Post

Common Network Response State Codes

4-4 Loading Web Content

Code demonstration:

//
//  ViewController.m
//  MyBrowser
//
//  Created by zc on 2017/6/2.
//  Copyright 2017 com.zccoder. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UISearchBarDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.view setBackgroundColor:[UIColor colorWithRed:0.776 green:0.776 blue:0.8 alpha:1.0]];
    
    // Create and initialize search boxes
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(15, 34,self.view.frame.size.width - 15 * 2 -60, 44)];
    // Prompt text
    _searchBar.placeholder = @"http://www.baidu.com";
    _searchBar.backgroundColor = [UIColor clearColor];
    _searchBar.delegate = self;
    [self.view addSubview:_searchBar];
    
    // Create and initialize search buttons
    _searchButton = [[UIButton alloc] initWithFrame:CGRectMake(_searchBar.frame.origin.x + _searchBar.frame.size.width + 10, 41, 60, 30)];
    _searchButton.backgroundColor = [UIColor clearColor];
    [_searchButton setTitle:@"search" forState:UIControlStateNormal];
    [_searchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _searchButton.layer.cornerRadius = 5.0;
    _searchButton.layer.borderColor = [UIColor blackColor].CGColor;
    _searchButton.layer.borderWidth = 1.0;
    // Adding Events
    [_searchButton addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_searchButton];

    // Create and initialize web pages
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 85, self.view.frame.size.width, self.view.frame.size.height - 85)];
    _webView.backgroundColor = [UIColor greenColor];
    [self.view addSubview:_webView];
    
}

// Search button click event
- (void)searchAction:(id)sender{
    NSLog(@"Search button click");
    [self loadWebContent];

}

// Receive callbacks by clicking the keyboard search button
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"searchBarSearchButtonClicked");
    [self loadWebContent];

}

// Loading Web Content
- (void) loadWebContent{
    
    // Release the first responder and close the keyboard
    [_searchBar resignFirstResponder];
    
    NSString *urlText = [_searchBar text];
    NSURL *url = [NSURL URLWithString:urlText];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSLog(@"Loading:%@",urlText);
    [_webView loadRequest:request];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

Chapter V: Summary

5-1 Summary

summary

Introduction to HTTP
 HTTP effect
 GET & POST Request
 UIWebView uses

Posted by no_one on Mon, 24 Jun 2019 12:35:18 -0700