网络
程序员文章站
2022-04-29 16:37:13
...
基础
NSURL *url = [NSURL URLWithString:@""];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//设置请求方法
request.HTTPMethod = @"POST";//默认为GET方法
//设置请求体
NSString *[email protected]"123";
NSString *[email protected]"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];