iOS联网方式

说明: 地址请查询API手册

iOS8以前的联网方式


同步请求

- (void) LoginButtonClicked:(UIButton *) sender{
    NSString *username = _uidField.text;
    NSString *password = _pwdField.text;
    // 文本框输入的信息作为参数传入
    NSString *urlStr = [NSString stringWithFormat:@"http://baidu.com/login.php?username=%@&password=%@",username,password];
    // 1.创建统一资源定位符
    NSURL *url = [NSURL URLWithString:urlStr];
    // 2.创建一个请求对象
    // 第一个参数:统一资源定位符
    // 第二个参数:缓存策略
    // 第三个参数:请求超时时间
    NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];
    // 3.通过连接对象发送请求
    // 同步请求(返回NSData) - 阻塞式请求(代码会在此阻塞直到服务器完成响应或超时)
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
    // 4.解析数据
    if (!error) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:1 error:nil];
        if ([dict[@"code"] isEqualToString:@"login_success"]) {
            NSLog(@"成功");
        }
        else{
            NSLog(@"失败");
        }
    }
    else{
        // 发生错误,打印错误日志
        NSLog(@"%@", error);
    }
}

异步请求

- (IBAction)registerButtonClicked:(UIButton *)sender {
    sender.enabled = NO;
    NSString *username = _uidField.text;
    NSString *password = _pwdField.text;
    NSString *email = _emailField.text;
    // 如果用户名有非ASCII字符需要转换成对应的百分号编码
    NSString *urlStr = [NSString stringWithFormat:@"http://baidu.com/login.php?username=%@&password=%@&email=%@",[username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], password, email];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:5];
    // 异步请求(返回viod) - 非阻塞式请求(代码会往下执行 当收到服务器数据时通过block回调处理服务器返回的数据)
    // 第一个参数:请求对象
    // 第二个参数:操作队列(异步请求操作放在哪个队列中执行)
    // 第三个参数:Block回调(处理服务器返回数据)
    [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:1 error:nil];
            if ([dict[@"code"] isEqualToString:@"registered"]) {
                NSLog(@"成功");
            }
            else{
                NSLog(@"失败");
            }
        }
        else{
            // 发生错误,打印错误日志
            NSLog(@"%@",connectionError);
        }
        sender.enabled = YES;
    }];
}

NSURLConnection

- (void) loadUserInfo{
    NSString *urlStr = @"http://www.baidu.com";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url cachePolicy:0 timeoutInterval:5];
    // 创建连接对象
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
    // 开始连接(该方法是异步请求)
    [conn start];
    
    // 取消连接
    //[conn cancel];
}
// 收到服务器响应的回调方法(只执行一次)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    // 首先定义了一个NSMutableData *mData的成员变量
    if (!mData) {
        mData = [NSMutableData data];
    }
    else{
        // 清空所有数据
        mData.length = 0;
    }
}

// 收到服务器数据的回调方法(多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    // 提示:如果传输的数据量较大 该方法有可能会对此执行
    [mData appendData:data];
}

// 服务器数据传输完毕的回调方法(只执行一次)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    // 解析数据刷新视图
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:mData options:1 error:nil];
    GPUserInfo *userInfo = [[GPUserInfo alloc] init];
    [userInfo setValuesForKeysWithDictionary:dict];
}

NSURLSession

GET请求

使用NSURLSession发送GET请求方法:

  1. 确定请求路径,参数直接写在后面(?params1=123¶ms2=456)
  2. 创建请求对象NSURLRequest
  3. 创建会话对象NSURLSession
  4. 创建请求任务NSURLSessionDataTask
  5. 执行任务
  6. 数据处理

示例代码:

- (void) GETMethod{
    // 1.创建请求路径
    NSString *strUrl = @"http://servicebeta.cn/search/search_id?searchword=世界&appId=4c5c510f9f43aa";
    
    NSURL *url = [NSURL URLWithString:strUrl];
    // 2.创建一个网络请求
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    // 3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    // 4.根据会话对象,创建一个Task任务:
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            // 从服务器获取到的数据data进行相应的处理
            NSString *tempStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",tempStr);
        }
        else{
            // 数据请求失败处理
            NSLog(@"%ld %@",error.code, error.localizedDescription);
        }
    }];
    // 5.执行任务
    [dataTask resume];
    // 任务挂起(暂停)
    //[dataTask suspend];
    // 任务取消
    //[dataTask cancel];
}

POST请求

使用NSURLSession发送POST请求方法:

  1. 确定请求路径(这里不写?参数)
  2. 创建可变的请求对象NSMutableURLRequest
  3. 修改请求方法为POST(默认包含了请求头和请求方法GET,GET请求时此步骤省略)
  4. 设置请求体(GET请求时此步骤省略)
  5. 创建会话对象NSURLSession
  6. 创建请求任务NSURLSessionDataTask
  7. 执行任务
  8. 数据处理

示例代码:

- (void) POSTMethod{
    // 1.创建请求路径
    NSString *strUrl = @"http://servicebeta.cn/search/search_id";
    NSURL *url = [NSURL URLWithString:strUrl];
    
    // 2.创建一个网络请求, 并设置请求方法和请求参数
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];
    request.HTTPMethod = @"POST";
    NSString *args = @"searchword=世界&appId=4c5c510f9f43aa";
    request.HTTPBody = [args dataUsingEncoding:NSUTF8StringEncoding];
    
    // 3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    // 4.根据会话对象,创建一个Task任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            // 从服务器获取到的数据data进行相应的处理
            NSString *tempStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",tempStr);
        }
        else{
            // 数据请求失败处理
            NSLog(@"%ld %@",error.code, error.localizedDescription);
        }
    }];
    // 5.执行任务
    [dataTask resume];
}

URLSession

@interface GPAlbumViewController (){
    // 所有的联网的配置都可以保存在该对象中
    // 该对象最好放到一个单例或者上下文中使其全局可见
    NSURLSessionConfiguration *config;
}

@end
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 在这里设置config的属性

    // NSURLSessionConfig对象可以保存公共设置
    // 默认配置
    config = [NSURLSessionConfiguration defaultSessionConfiguration];
    // 创建一个无痕浏览的配置 不保存任何数据到保存
    //config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    // 创建一个后台运行的配置
    //config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"foo"];
    //config.HTTPAdditionalHeaders = @{@"apikey":@"你自己的key"};
    // 没电可以自动断开
    //config.discretionary = YES;
    
}
- (void)creatAlbum:(NSString *) name{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://baidu.com/create_album.php?albumname=%@&privacy=0",[name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    // 通过NSURLSessionConfiguration对象创建NSURLSession对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:1 error:nil];
            if ([dict[@"code"] isEqualToString:@"do_success"]) {
                NSLog(@"成功");
            }
            else{
                NSLog(@"失败");
            }
        }
        else{
            NSLog(@"%@",error);
        }
    }];
    // 执行任务
    [task resume];
}

AFNetworking

-(void) uploadphoto:(UIImage *) photoImage{
   
    NSDictionary *params = @{@"albumid":@(_albumId)};
    
    // 通过AFHTTPRequestSerializer对象创建请求对象
    // AFHTTPRequestSerializer对象创建请求的方法有五个参数:
    // 第一个参数: 设置请求方法(如果上传表单数据中如果有附件(二进制数据)必须使用POST请求)
    // 第二个参数: 统一资源定位符
    // 第三个参数: 提交给服务器的请求参数(表单中的参数)
    // 第四个参数: 提交给服务器的二进制数据(表单中的附件)
    // 第五个参数: NSError对象指针的指针
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://baidu.com/upload_photo.php" parameters:params constructingBodyWithBlock:^(id formData) {
        // 通过UUID生成全局唯一的文件名
        NSString *filename = [NSString stringWithFormat:@"%@.png",[NSUUID UUID].UUIDString];
        // 将UIImage对象转成NSData对象(二进制数据)
        NSData *data = UIImagePNGRepresentation(photoImage);
        // 第一个参数:上传的二进制数据
        // 第二个参数:上传文件对应的参数名(通过查API手册获得)
        // 第三个参数:上传文件的文件名(这个名字通常没用,因为服务器通常会用自己的命名规则给上传的文件起名字来避免名字冲突)
        // 第四个参数:MIME类型(告知服务器上传的文件的类型)
        [formData appendPartWithFileData:data name:@"attach" fileName:filename mimeType:@"image/png"];
    } error:nil];
    
    // 通过会话配置对象创建AFNetworking的会话管理器对象
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[GPSNSContext sharedSNSContext].configure];
    // 表示完成进度的对象
    NSProgress *progress = nil;
    
    AFHTTPResponseSerializer *serializer = manager.responseSerializer;
    serializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"text/plain", nil];
    
    // 创建会话任务(获取数据任务、下载任务、上传任务)
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        
        if (!error) {
            hud.labelText = responseObject[@"message"];
            [hud hide:YES afterDelay:2];
        }
        else{
            NSLog(@"%@",error);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            // 关闭网络活动指示器
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
    }];
    
    // 在状态栏显示网络活动指示器
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    [uploadTask resume];
}
- (void) loadDataModel{
    if (!dataArray) {
        dataArray = [NSMutableArray array];
    }
    // 创建会话管理器对象(AFNetwoking提供的专门用于管理NSURLSession的对象)
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[GPSNSContext sharedSNSContext].configure];

    // 设置AFNetwork支持的响应内容的MIME类型
    // text/html - 超文本
    // text/plain - 纯文本
    // application/json - JSON
    // text/xml - XML
    // 有很多服务器在返回json数据的时候没有指定MIME类型是application/json类型 这样的话AFNetworking会报错 因为AFNetworking默认只支持application/json类型
    AFHTTPResponseSerializer *serializer = manager.responseSerializer;
    serializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"text/plain", nil];
    
    NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://baidu.com/photo_list.php?uid=%ld&id=%ld",[GPSNSContext sharedSNSContext].uid,_albumId]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (!error) {
            for (NSDictionary *photoDict in responseObject[@"photos"]) {
                GPPicture *model = [GPPicture yy_modelWithDictionary:photoDict];
                [dataArray addObject:model];
            }
            // 这里要使用异步 如果使用dispatch_sync会卡
            dispatch_async(dispatch_get_main_queue(), ^{
                [myCollView reloadData];
            });
        }
        else {
            NSLog(@"Error: %@", error);
        }
    }];
    [dataTask resume];
}

iOS9访问http协议的URL需要修改配置文件

方法一:你可以在Info.plist 配置中添加或者修改XML源码:

iOS联网方式_第1张图片
xml.png

方法二:在 info.plist 文件中配置显示如下:

iOS9.png

你可能感兴趣的:(iOS联网方式)