IOS開發基礎之NSURLSession的使用
服務器我們選用的是tomcat服務器。
所有項目info.plist加入
<key>NSAppTransportSecurity
</key><dict><key>NSAllowsArbitraryLoads
</key><true/></dict>
第一章:
- NSURLSession的使用演示之 dataTask 的使用 源碼
#import "ViewController.h"
@interface ViewController
()
@end
@implementation ViewController
- (void)viewDidLoad
{[super viewDidLoad
];
}
- (void)touchesBegan
:(NSSet
<UITouch
*> *)touches withEvent
:(UIEvent
*)event
{[self dataTask3
];
}
-(void)dataTask3
{NSURL
*url
=[NSURL URLWithString
:@"http://localhost:8080/DaJunServer/login"];NSMutableURLRequest
*request
= [NSMutableURLRequest requestWithURL
:url
];request
.HTTPMethod
= @"post";NSString
*body
= @"username=123&pwd=123";request
.HTTPBody
= [body dataUsingEncoding
:NSUTF8StringEncoding
];[[[NSURLSession sharedSession
] dataTaskWithRequest
:request completionHandler
:^(NSData
* _Nullable data
, NSURLResponse
* _Nullable response
, NSError
* _Nullable error
) {id json
= [NSJSONSerialization JSONObjectWithData
:data options
:0 error
:NULL];NSLog(@"%@",json
);}] resume
];
}
-(void)dataTask2
{NSURL
*url
= [NSURL URLWithString
:@"http://localhost:8080/DaJunServer/video?method=get&type=JSON"];[[[NSURLSession sharedSession
] dataTaskWithURL
:url completionHandler
:^(NSData
* _Nullable data
, NSURLResponse
* _Nullable response
, NSError
* _Nullable error
) {id json
= [NSJSONSerialization JSONObjectWithData
:data options
:0 error
:NULL];NSLog(@"%@",json
);}] resume
];
}
-(void)dataTask1
{NSURL
*url
= [NSURL URLWithString
:@"http://localhost:8080/DaJunServer/video?method=get&type=JSON"];NSURLSessionDataTask
*dataTask
= [[NSURLSession sharedSession
] dataTaskWithURL
:url completionHandler
:^(NSData
* _Nullable data
, NSURLResponse
* _Nullable response
, NSError
* _Nullable error
) {id json
= [NSJSONSerialization JSONObjectWithData
:data options
:0 error
:NULL];NSLog(@"%@",json
);}];[dataTask resume
];
}
@end
第二章:
- NSURLSession的使用演示之 downloadTask 的使用 下載進度的 源碼
#import "ViewController.h"
@interface ViewController
() <NSURLSessionDownloadDelegate
>
@property(nonatomic
,strong
)NSURLSession
*session
;
@end
@implementation ViewController
- (NSURLSession
*)session
{if(_session
==nil
){NSURLSessionConfiguration
*config
= [NSURLSessionConfiguration defaultSessionConfiguration
];_session
=[NSURLSession sessionWithConfiguration
:config delegate
:self delegateQueue
:[NSOperationQueue mainQueue
]];}return _session
;
}
- (void)viewDidLoad
{[super viewDidLoad
];
}
- (void)touchesBegan
:(NSSet
<UITouch
*> *)touches withEvent
:(UIEvent
*)event
{[self downloadTask
];
}
-(void)downloadTask
{NSURL
*url
=[NSURL URLWithString
:@"http://localhost:8080/DaJunServer/resources/videos/minion_01.mp4"];
[[self.session downloadTaskWithURL
:url
] resume
];
}
- (void)URLSession
:(NSURLSession
*)session downloadTask
:(NSURLSessionDownloadTask
*)downloadTask didFinishDownloadingToURL
:(NSURL
*)location
{NSLog(@"%@",[NSThread currentThread
]);NSLog(@"下載完成 %@",location
);
}
- (void)URLSession
:(NSURLSession
*)session downloadTask
:(NSURLSessionDownloadTask
*)downloadTask didResumeAtOffset
:(int64_t
)fileOffset expectedTotalBytes
:(int64_t
)expectedTotalBytes
{NSLog(@"續傳");
}
- (void)URLSession
:(NSURLSession
*)session downloadTask
:(NSURLSessionDownloadTask
*)downloadTask didWriteData
:(int64_t
)bytesWritten totalBytesWritten
:(int64_t
)totalBytesWritten totalBytesExpectedToWrite
:(int64_t
)totalBytesExpectedToWrite
{float process
=totalBytesWritten
* 1.0 / totalBytesExpectedToWrite
;NSLog(@"下載進度 = %f",process
);
}
@end
第三章
#import "ViewController.h"@interface ViewController
() <NSURLSessionDownloadDelegate
>
@property(nonatomic
,strong
)NSURLSession
*session
;
@property(nonatomic
,strong
)NSURLSessionDownloadTask
*downloadTask
;
@property(nonatomic
,strong
) NSData
*resumeData
;
@property (weak
, nonatomic
) IBOutlet UIProgressView
*progressView
;
@end
@implementation ViewController
- (NSURLSession
*)session
{if(_session
==nil
){NSURLSessionConfiguration
*config
= [NSURLSessionConfiguration defaultSessionConfiguration
];_session
=[NSURLSession sessionWithConfiguration
:config delegate
:self delegateQueue
:[NSOperationQueue mainQueue
]];}return _session
;
}
- (IBAction
)startClick
:(id
)sender
{[self download
];
}
- (IBAction
)pauseClick
:(id
)sender
{[self.downloadTask cancelByProducingResumeData
:^(NSData
* _Nullable resumeData
) {self.resumeData
= resumeData
;NSString
*path
= [NSTemporaryDirectory() stringByAppendingPathComponent
:@"456.tmp"];[self.resumeData writeToFile
:path atomically
:YES
];self.downloadTask
= nil
;NSLog(@"%@",resumeData
);}];
}
- (IBAction
)resumeClick
:(id
)sender
{NSString
*path
= [NSTemporaryDirectory() stringByAppendingPathComponent
:@"456.tmp"];NSFileManager
*fileManger
=[NSFileManager defaultManager
];if([fileManger fileExistsAtPath
:path
]){self.resumeData
= [NSData dataWithContentsOfFile
:path
];}if(self.resumeData
== nil
){return;}self.downloadTask
= [self.session downloadTaskWithResumeData
:self.resumeData
];[self.downloadTask resume
];self.resumeData
= nil
;
}
- (void)viewDidLoad
{[super viewDidLoad
];
}
-(void)download
{NSURL
*url
=[NSURL URLWithString
:@"http://localhost:8080/DaJunServer/resources/videos/minion_01.mp4"];NSURLSessionDownloadTask
*downloadTask
= [self.session downloadTaskWithURL
:url
];self.downloadTask
= downloadTask
;[downloadTask resume
];
}
- (void)URLSession
:(NSURLSession
*)session downloadTask
:(NSURLSessionDownloadTask
*)downloadTask didFinishDownloadingToURL
:(NSURL
*)location
{NSLog(@"%@",[NSThread currentThread
]);NSLog(@"下載完成 %@",location
);
}
- (void)URLSession
:(NSURLSession
*)session downloadTask
:(NSURLSessionDownloadTask
*)downloadTask didResumeAtOffset
:(int64_t
)fileOffset expectedTotalBytes
:(int64_t
)expectedTotalBytes
{NSLog(@"續傳");
}
- (void)URLSession
:(NSURLSession
*)session downloadTask
:(NSURLSessionDownloadTask
*)downloadTask didWriteData
:(int64_t
)bytesWritten totalBytesWritten
:(int64_t
)totalBytesWritten totalBytesExpectedToWrite
:(int64_t
)totalBytesExpectedToWrite
{float process
=totalBytesWritten
* 1.0 / totalBytesExpectedToWrite
;NSLog(@"下載進度 = %f",process
);self.progressView
.progress
= process
;
}
@end
總結
以上是生活随笔為你收集整理的IOS开发基础之NSURLSession的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。