网络

作者: yaya_pangdun | 来源:发表于2016-07-25 18:18 被阅读12次

基础

NSURL *url = [NSURL URLWithString:@""];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//设置请求方法
request.HTTPMethod = @"POST";//默认为GET方法
//设置请求体
NSString *name=@"123";
NSString *pwd=@"123";0.
NSString *par=[NSString stringWithFormat:@"username=%@&pwd=%@", name, pwd];

//转化成可用数据
NSData *data = [par dataUsingEncoding:NSUTF8StringEncoding];
//设置请求体
request.HTTPBody = data;

//设置请求头
[request setValue:@"iPhone 88客户端" forHTTPHeaderField:@"User-Agent"];

默认情况下不能传输中文数据,设置编码转换

str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

发送JSON给服务器

NSDictionary *orderInfo = @{
      @"shop_id":@"1234",
      @"shop_name":@"呜呜",
      @"user_id":@"xu", nil
};

NSData *json = [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];

request.HTTPBody = json;

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

网络状态

Reachability *wifi = [Reachability reachabilityForLocalWiFi];
NetworkStatus wifiStatus = wifi.currentReachabilityStatus;
if (wifiStatus != NotReachable) {
        NSLog(@"WIFI连通");
}

随时监听

@interface ViewController ()
@property (nonatomic, strong) Reachability *reach;
@end
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChange) name:kReachabilityChangedNotification object:nil];

self.reach = [Reachability reachabilityForInternetConnection];
    
[self.reach startNotifier];
-(void)reachabilityChange
{
    NSLog(@"网络状态改变了");
}

大文件节省内存下载

NSFileManager *fileMgr = [NSFileManager defaultManager];

NSString *fileDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

NSString *filePath = [fileDir stringByAppendingPathComponent:@"video.zip"];

[fileMgr createFileAtPath:filePath contents:nil attributes:nil];
//NSFileHandle *
self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];

每次读取到数据

[self.writeHandle seekToEndOfFile];
[self.writeHandle writeData:data];

NSURLSession使用

NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@"www.baidu.com"];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *d = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", d);
}];
    
[task resume];

进行文件下载(自动小内存下载)

NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@"www.baidu.com"];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //如果不在这个block中做操作,默认下载的临时文件会被清除
        NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        NSString *filePath = [cache stringByAppendingPathComponent:response.suggestedFilename];
        
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        [fileMgr moveItemAtPath:location.path toPath:filePath error:nil];
}];

没有下载进度,可以进行改进(利用代理)

NSURLSessionConfiguration *cf = [NSURLSessionConfiguration defaultSessionConfiguration];
    
NSURLSession *session = [NSURLSession sessionWithConfiguration:cf delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"www.baidu.com"]];
    
[task resume];
<NSURLSessionDownloadDelegate>

实现代理方法

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    //下载完成,location为下载完成的临时文件
    NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    NSString *filePath = [cache stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    
    [fileMgr moveItemAtPath:location.path toPath:filePath error:nil];
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
    //恢复下载时调用
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //下载进度
    //bytesWritten 本次写入多少
    //totalBytesWritten 总计写入多少
    //totalBytesExpectedToWrite 文件总大小
}

断点下载

__weak typeof(self) weakSelf = self;
[self.task cancelByProducingResumeData:^(NSData *resumeData){
      weakSelf.resumeData =resumeData;
      weakSelf.task = nil;
}];
-(void)resume
{
      self.task = [self.session downloadTaskWithResumeData:self.resumeData];
      self.resumeData = nil;
}

只需要一个session就可以。所以封装代码进行懒加载。

-(NSURLSession *)session
{
    if (!_session) {
        NSURLSessionConfiguration *cf = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        NSURLSession *session = [NSURLSession sessionWithConfiguration:cf delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        _session = session;
    }
    return _session;
}

文件上传

#define XUFileBoundary @"xujiguang"
#define XUNewLine @"\r\n"
#define XUEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding];

设置上传参数

AFNetworking使用

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//params为dictionary
[manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
    
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
}];

上传文件

//1。创建管理者对象 
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

NSDictionary *dict = @{@"username":@"1234"};

NSString *urlString = @"22222";

[manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
   UIImage *iamge = [UIImage imageNamed:@"123.png"];
   NSData *data = UIImagePNGRepresentation(iamge);
   [formData appendPartWithFileData:data name:@"file" fileName:@"123.png" mimeType:@"image/png"];
   //[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"文件地址"] name:@"file" fileName:@"1234.png" mimeType:@"application/octet-stream" error:nil];å
} progress:^(NSProgress * _Nonnull uploadProgress) {
   //打印上传进度
   NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

}];

AFN监听网络状态

AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];

[manager setReachabilityStatusChangeBlock:^(AFNetworkReachability status) {
   switch(status) {
      case AFNetworkReachabilityStatusReachableViaWiFi:
(ViaWWAN、NotReachable、Unknown)
   }
}];

[manager startMonitoring];

相关文章

  • 网络!网络!

    ...

  • 网络,网络

    敲击键盘,滴滴答答,行云流水,我和你在无形的世界中产生了存在着的联系。落日,似乎看不到,看到的,只是手中的那块屏幕...

  • 网络?网络!

    网络是一片浩瀚的海,在网络初建之时,如一片处女地,在上面初生了各种各样文化的苗,虽星星点点却也清新。或许是审...

  • 网络—网络婴儿

    在餐馆你可能看到,专注的母亲盯着手机,而在她臂弯里的儿童却不知所措;在家里,母亲在厨房里忙碌,而婴儿在拨弄着平板自...

  • 网络啊网络

    下午,天突降大雨。 其时我正打开电脑在听音乐,声音戛然而止,我以为是网络卡住了,就照样一边忙碌着一边等待音乐声再次...

  • 网络-网络层

    网络层 网络层数据包(IP数据包,Packet)由首部、数据2部分组成数据:很多时候是由传输层传递下来的数据段(S...

  • 测试网络

    测试网络测试网络测试网络测试网络测试网络测试网络

  • 网络 和网络笔记

    ifconfig -a 查看物理网卡硬件地址 比如 ether 00:0c:29:ab:6e:72 更改M...

  • 【网络】集群网络排错

    前几天实验室网络抽风,卡的要死要死的,做实验也做的要死要死的(跟十几台小集群在一个屋里通宵,这种酸爽简直终身难忘)...

  • Android网络——网络状态

    1. 判断网络是否可用 2. 判断网络类型

网友评论

      本文标题:网络

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