测试已测试 | ✓ |
Lang语言 | Obj-CObjective-C |
许可证 | MIT |
发布上次发布 | 2014 年 12 月 |
由 Tobias Sundstrand 维护。
依赖项 | |
AFNetworking/Security | >= 0 |
可达性 | >= 0 |
因为我想要看看 NSURLSession 的工作原理。
确保将它添加到您的应用程序代理中。它将确保您的应用程序挂起时完成上传/下载的完成块。
#import "TSNetworking.h"
- (void)application:(UIApplication *)application
handleEventsForBackgroundURLSession:(NSString *)identifier
completionHandler:(void (^)())completionHandler
{
[TSNetworking backgroundSession].sessionCompletionHandler = completionHandler;
}
[[TSNetworking foregroundSession] setBaseURLString:kBaseURLString];
[[TSNetworking foregroundSession] setBasicAuthUsername:nil withPassword:nil];
[[TSNetworking foregroundSession] addSessionHeaders:@{@"all":@"nightlong"}]; // sticks around forever, used in each request
这些设置在应用程序运行期间有效
[[TSNetworking foregroundSession] removeAllSessionHeaders];
[TSNetworking foregroundSession] /* for all your regular GETs, POSTs. You are given an NSObject as the result.
OR for uploading NSData in the foreground. */
- OR -
[TSNetworking backgroundSession] /* for all your background downloads and (local NSURL) uploads. Uses funky new NSURLSession features to run while your apps if minimized, no need to pause and serialise your downloads on applicationDidEnterBackground */
成功和错误块在苹果决定线程上执行。如果您在这些块中进行 UI 变更,建议您使用 dispatch_async 并获取主队列。对新手玩家的警告:永远不要在块内部引用 self,使用这种样式以避免保留循环
__weak typeof(self) weakSelf = self;
TSNetworkSuccessBlock successBlock = ^(NSObject *resultObject, NSMutableURLRequest *request, NSURLResponse *response) {
__strong typeof(weakSelf) strongSelf = weakSelf;
[strongSelf sendAMessage];
};
TSNetworkSuccessBlock successBlock = ^(NSObject *resultObject, NSMutableURLRequest *request, NSURLResponse *response) {
NSLog(@"We got ourselves a: %@", resultObject);
};
TSNetworkErrorBlock errorBlock = ^(NSObject *resultObject, NSError *error, NSMutableURLRequest *request, NSURLResponse *response) {
switch (error.code) {
case 401:
NSLog(@"Mannn");
break;
default:
break;
}
};
[[TSNetworking foregroundSession] performDataTaskWithRelativePath:nil
withMethod:HTTP_METHOD_GET
withParameters:nil
withAddtionalHeaders:@{@"Content-Type":@"application/json"}
withSuccess:successBlock
withError:errorBlock];
TSNetworkSuccessBlock successBlock = ^(NSObject *resultObject, NSMutableURLRequest *request, NSURLResponse *response) {
// resultObject will probably be a JSON dictionary
};
TSNetworkErrorBlock errorBlock = ^(NSObject *resultObject, NSError *error, NSMutableURLRequest *request, NSURLResponse *response) {
NSLog(@"%@", error.localizedDescription); // tells you what the problem was, i.e. offline
};
[[TSNetworking foregroundSession] performDataTaskWithRelativePath:nil
withMethod:HTTP_METHOD_POST
withParameters:@{@"key": @"value"}
withAddtionalHeaders:nil
withSuccess:successBlock
withError:errorBlock];
TSNetworkSuccessBlock successBlock = ^(NSObject *resultObject, NSMutableURLRequest *request, NSURLResponse *response) {
// sweet, resultObject is a (local) NSURL for what we just downloaded
};
TSNetworkErrorBlock errorBlock = ^(NSObject *resultObject, NSError *error, NSMutableURLRequest *request, NSURLResponse *response) {
//same old handling
};
TSNetworkDownloadTaskProgressBlock progressBlock = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
NSLog(@"Download written: %lld, total written: %lld, total expected: %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
};
NSURLSessionDownloadTask *task = [[TSNetworking backgroundSession] downloadFromFullPath:@"https://archive.org/download/1mbFile/1mb.mp4"
toPath:destinationPath
withAddtionalHeaders:nil
withProgressBlock:progressBlock
withSuccess:successBlock
withError:errorBlock];
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"ourLord" ofType:@"jpg"];
TSNetworkSuccessBlock successBlock = ^(NSObject *resultObject, NSMutableURLRequest *request, NSURLResponse *response) {
//resultObject is whatever the server responded with, could be JSON, HTML, whatever
};
TSNetworkErrorBlock errorBlock = ^(NSObject *resultObject, NSError *error, NSMutableURLRequest *request, NSURLResponse *response) {
//same old handling
};
TSNetworkDownloadTaskProgressBlock progressBlock = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
NSLog(@"uploaded: %lld, total written: %lld, total expected: %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
};
NSURLSessionUploadTask *uploadTask = [[TSNetworking backgroundSession] uploadInBackgroundFromLocalPath:sourcePath
toPath:kMultipartUpload
withAddtionalHeaders:nil
withProgressBlock:progressBlock
withSuccess:successBlock
withError:errorBlock];
// or
NSFileManager *fm = [NSFileManager new];
NSData *data = [fm contentsAtPath:sourcePath];
[[TSNetworking foregroundSession] uploadInForegroundData:data
toPath:kMultipartUpload
withAddtionalHeaders:nil
withProgressBlock:progressBlock
withSuccess:successBlock
withError:errorBlock];