Skip to content

Commit f62b75e

Browse files
author
zhuhao
committedSep 19, 2017
添加下载请求的处理逻辑
1 parent 5231550 commit f62b75e

8 files changed

+297
-68
lines changed
 

‎ZHNetWorking.xcodeproj/project.pbxproj

+12-2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
objects = {
88

99
/* Begin PBXBuildFile section */
10+
8630D73B1F6BD133008E3982 /* user_growth_gift@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 8630D7391F6BD133008E3982 /* user_growth_gift@2x.png */; };
11+
8630D73C1F6BD133008E3982 /* user_growth_gift@3x.png in Resources */ = {isa = PBXBuildFile; fileRef = 8630D73A1F6BD133008E3982 /* user_growth_gift@3x.png */; };
1012
86458D4E1F31D487006F7FF3 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 86458D4D1F31D487006F7FF3 /* main.m */; };
1113
86458D511F31D487006F7FF3 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 86458D501F31D487006F7FF3 /* AppDelegate.m */; };
1214
86458D541F31D487006F7FF3 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 86458D531F31D487006F7FF3 /* ViewController.m */; };
@@ -19,6 +21,8 @@
1921
/* End PBXBuildFile section */
2022

2123
/* Begin PBXFileReference section */
24+
8630D7391F6BD133008E3982 /* user_growth_gift@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "user_growth_gift@2x.png"; sourceTree = "<group>"; };
25+
8630D73A1F6BD133008E3982 /* user_growth_gift@3x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "user_growth_gift@3x.png"; sourceTree = "<group>"; };
2226
86458D491F31D487006F7FF3 /* ZHNetWorking.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ZHNetWorking.app; sourceTree = BUILT_PRODUCTS_DIR; };
2327
86458D4D1F31D487006F7FF3 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
2428
86458D4F1F31D487006F7FF3 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
@@ -33,6 +37,7 @@
3337
86566E071F67C89800C2D52B /* ZHRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ZHRequest.m; sourceTree = "<group>"; };
3438
86566E091F67D34A00C2D52B /* ZHRequestManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZHRequestManager.h; sourceTree = "<group>"; };
3539
86566E0A1F67D34A00C2D52B /* ZHRequestManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ZHRequestManager.m; sourceTree = "<group>"; };
40+
869AEC5B1F6B7A9B00833A09 /* ZHRequestDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZHRequestDelegate.h; sourceTree = "<group>"; };
3641
9380F8EE815297784EA124FB /* libPods-ZHNetWorking.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-ZHNetWorking.a"; sourceTree = BUILT_PRODUCTS_DIR; };
3742
A956FAE5D41D472CECCB892B /* Pods-ZHNetWorking.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ZHNetWorking.debug.xcconfig"; path = "Pods/Target Support Files/Pods-ZHNetWorking/Pods-ZHNetWorking.debug.xcconfig"; sourceTree = "<group>"; };
3843
E56DDE47A214ABD51D5977EE /* Pods-ZHNetWorking.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ZHNetWorking.release.xcconfig"; path = "Pods/Target Support Files/Pods-ZHNetWorking/Pods-ZHNetWorking.release.xcconfig"; sourceTree = "<group>"; };
@@ -53,6 +58,8 @@
5358
86458D401F31D487006F7FF3 = {
5459
isa = PBXGroup;
5560
children = (
61+
8630D7391F6BD133008E3982 /* user_growth_gift@2x.png */,
62+
8630D73A1F6BD133008E3982 /* user_growth_gift@3x.png */,
5663
86458D4B1F31D487006F7FF3 /* ZHNetWorking */,
5764
86458D4A1F31D487006F7FF3 /* Products */,
5865
9DFAA07CE7468C01A054B352 /* Pods */,
@@ -79,6 +86,7 @@
7986
86566E071F67C89800C2D52B /* ZHRequest.m */,
8087
86566E091F67D34A00C2D52B /* ZHRequestManager.h */,
8188
86566E0A1F67D34A00C2D52B /* ZHRequestManager.m */,
89+
869AEC5B1F6B7A9B00833A09 /* ZHRequestDelegate.h */,
8290
86458D551F31D487006F7FF3 /* Main.storyboard */,
8391
86458D581F31D487006F7FF3 /* Assets.xcassets */,
8492
86458D5A1F31D487006F7FF3 /* LaunchScreen.storyboard */,
@@ -177,7 +185,9 @@
177185
files = (
178186
86458D5C1F31D487006F7FF3 /* LaunchScreen.storyboard in Resources */,
179187
86458D591F31D487006F7FF3 /* Assets.xcassets in Resources */,
188+
8630D73B1F6BD133008E3982 /* user_growth_gift@2x.png in Resources */,
180189
86458D571F31D487006F7FF3 /* Main.storyboard in Resources */,
190+
8630D73C1F6BD133008E3982 /* user_growth_gift@3x.png in Resources */,
181191
);
182192
runOnlyForDeploymentPostprocessing = 0;
183193
};
@@ -367,7 +377,7 @@
367377
INFOPLIST_FILE = ZHNetWorking/Info.plist;
368378
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
369379
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
370-
PRODUCT_BUNDLE_IDENTIFIER = "ZHNeworking-ttt";
380+
PRODUCT_BUNDLE_IDENTIFIER = "ZHNeworking-ttttttt";
371381
PRODUCT_NAME = "$(TARGET_NAME)";
372382
PROVISIONING_PROFILE_SPECIFIER = "";
373383
};
@@ -384,7 +394,7 @@
384394
INFOPLIST_FILE = ZHNetWorking/Info.plist;
385395
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
386396
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
387-
PRODUCT_BUNDLE_IDENTIFIER = "ZHNeworking-ttt";
397+
PRODUCT_BUNDLE_IDENTIFIER = "ZHNeworking-ttttttt";
388398
PRODUCT_NAME = "$(TARGET_NAME)";
389399
PROVISIONING_PROFILE_SPECIFIER = "";
390400
};

‎ZHNetWorking/Info.plist

+5-5
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,6 @@
22
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
33
<plist version="1.0">
44
<dict>
5-
<key>NSAppTransportSecurity</key>
6-
<dict>
7-
<key>NSAllowsArbitraryLoads</key>
8-
<true/>
9-
</dict>
105
<key>CFBundleDevelopmentRegion</key>
116
<string>en</string>
127
<key>CFBundleExecutable</key>
@@ -25,6 +20,11 @@
2520
<string>1</string>
2621
<key>LSRequiresIPhoneOS</key>
2722
<true/>
23+
<key>NSAppTransportSecurity</key>
24+
<dict>
25+
<key>NSAllowsArbitraryLoads</key>
26+
<true/>
27+
</dict>
2828
<key>UILaunchStoryboardName</key>
2929
<string>LaunchScreen</string>
3030
<key>UIMainStoryboardFile</key>

‎ZHNetWorking/ViewController.m

+61-26
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@
99
#import "ViewController.h"
1010
#import "ZHRequest.h"
1111
#import "ZHRequestManager.h"
12-
@interface ViewController ()
12+
13+
#define kUserToken @"02b504cc5d6d4666be41e40f8946e1d6"
14+
15+
@interface ViewController ()<ZHRequestDelegate>
1316

1417
@end
1518

@@ -19,7 +22,7 @@ - (void)viewDidLoad {
1922
[super viewDidLoad];
2023

2124

22-
25+
// get 请求
2326
// NSDictionary * dic = @{
2427
// @"app" : @1,
2528
// @"deviceid" : @"18896d567674dbd24457a8ecb483cd5c5695667d",
@@ -34,31 +37,57 @@ - (void)viewDidLoad {
3437
//
3538
// NSString *urlStr = [NSString stringWithFormat:@"%@mobile/newstartup.ashx",[NSString stringWithFormat:@"https://mobilenc.app.autohome.com.cn/mobile_v%@/",@"7.6.0"]];
3639

40+
// for (int i= 1; i<2; i++) {
41+
// ZHRequest *req = [[ZHRequest alloc] init];
42+
// req.timeoutInterval = 20;
43+
// req.requestType = ZHRequest_Type_POST;
44+
// req.urlString = @"https://activity.app.autohome.com.cn/ugapi/api/guide/getNoticeRule";
45+
// req.priority = ZHRequest_Priority_Low;
46+
// if (i % 5 ==0) {
47+
// req.priority = ZHRequest_Priority_High;
48+
// }
49+
// req.delegate = self;
50+
// [req start];
51+
// }
52+
53+
54+
UIImage *imgData = [UIImage imageNamed:@"user_growth_gift"];
55+
56+
NSMutableDictionary * dic =[NSMutableDictionary dictionaryWithCapacity:7];
57+
[dic setValue:kUserToken forKey:@"userId"];
58+
[dic setValue:UIImagePNGRepresentation(imgData) forKey:@"file"];
59+
60+
[dic setValue:@"lisi" forKey:@"nickname"];
3761

62+
63+
NSString *urlStr = @"http://ebook.huakeyihui.com:8080/pod/mobile/user/uploadHead";
64+
65+
66+
67+
// post 请求登录
3868
// NSDictionary *dic = @{@"acount" : @"18809876543", @"password" : @"123456"};
3969
// NSString *urlStr = @"http://ebook.huakeyihui.com:8080/pod/mobile/user/login";
40-
//
41-
// ZHRequest *postRe = [[ZHRequest alloc] init];
42-
// postRe.urlString = urlStr;
43-
// postRe.params = dic;
44-
// postRe.requestType = ZHRequest_Type_POST;
45-
// [postRe start];
4670

47-
for (int i= 1; i<2; i++) {
48-
ZHRequest *req = [[ZHRequest alloc] init];
49-
req.timeoutInterval = 20;
50-
req.requestType = ZHRequest_Type_GET;
51-
req.urlString = @"https://activity.app.autohome.com.cn/ugapi/api/guide/getNoticeRule";
52-
req.priority = ZHRequest_Priority_Low;
53-
if (i % 5 ==0) {
54-
req.priority = ZHRequest_Priority_High;
55-
}
56-
57-
58-
[req start];
59-
60-
[req start];
61-
}
71+
72+
NSString *downloadStr = @"http://120.25.226.186:32812/resources/videos/minion_01.mp4";
73+
74+
ZHRequest *postRe = [[ZHRequest alloc] init];
75+
postRe.urlString = downloadStr;
76+
postRe.delegate = self;
77+
// postRe.params = dic;
78+
79+
80+
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
81+
82+
postRe.downloadProcess = ^(NSProgress *process) {
83+
NSLog(@"--------->%.2f",process.completedUnitCount/(process.totalUnitCount*1.0));
84+
};
85+
postRe.downloadPath = documentPath;
86+
postRe.requestType = ZHRequest_Type_GET;
87+
[postRe start];
88+
89+
90+
// http://120.25.226.186:32812/resources/videos/minion_01.mp4
6291

6392

6493
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
@@ -68,9 +97,15 @@ - (void)viewDidLoad {
6897
}
6998

7099

71-
- (void)didReceiveMemoryWarning {
72-
[super didReceiveMemoryWarning];
73-
// Dispose of any resources that can be recreated.
100+
- (void)requestFailed:(NSError *)error {
101+
102+
}
103+
104+
- (void)requestFinished:(ZHRequest *)request responseStr:(NSString *)responseStr {
105+
106+
}
107+
- (void)requestWillStart {
108+
74109
}
75110

76111

‎ZHNetWorking/ZHRequest.h

+19-7
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
//
88

99
#import "AFNetworking.h"
10-
10+
#import "ZHRequestDelegate.h"
1111
typedef NS_ENUM(NSInteger, ZHRequest_Type) {
1212
ZHRequest_Type_GET = 0,
1313
ZHRequest_Type_POST
@@ -23,8 +23,6 @@ typedef NS_ENUM(NSInteger, ZHRequest_RequestSerializerType) {
2323

2424
};
2525

26-
27-
2826
typedef NS_ENUM(NSInteger, ZHRequest_Priority) {
2927
ZHRequest_Priority_Default = 0,
3028
ZHRequest_Priority_High,
@@ -42,11 +40,11 @@ typedef NS_ENUM(NSInteger, ZHRequest_ResponseSerilalizerType) {
4240
};
4341

4442
typedef void (^ConstructingFormDataBlock)(id<AFMultipartFormData> formData);
45-
typedef void (^ProcessBlock)(NSProgress *process);
46-
typedef void (SuccessBlock) (id responseObj);
47-
typedef void (FailureBlock) (NSError *error);
43+
typedef void (^SuccessBlock) (id responseObj);
44+
typedef void (^FailureBlock) (NSError *error);
45+
typedef void (^DownloadProcessBlock)(NSProgress *process);
4846

49-
@interface ZHRequest : NSObject
47+
@interface ZHRequest : NSObject <ZHRequestDelegate>
5048

5149
@property(nonatomic, strong) NSURLSessionTask *sessionTask;
5250
@property(nonatomic, assign) NSInteger statusCode;
@@ -86,6 +84,20 @@ typedef void (FailureBlock) (NSError *error);
8684

8785
@property(nonatomic, assign) ZHRequest_ResponseSerilalizerType responseSerilalizerType;
8886

87+
/*!
88+
@property
89+
@abstract 下载文件的路径,如果设置该属性则会使用 downloadTask ,
90+
开始下载文件之前会将该路径的文件先移除
91+
*/
92+
@property(nonatomic, copy) NSString *downloadPath;
93+
/*!
94+
@property
95+
@abstract 下载文件的进度
96+
*/
97+
@property(nonatomic, copy) DownloadProcessBlock downloadProcess;
98+
99+
@property(nonatomic, weak) id<ZHRequestDelegate> delegate;
100+
89101
- (void)cancel;
90102

91103
- (void)start;

‎ZHNetWorking/ZHRequestDelegate.h

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
//
2+
// ZHRequestDelegate.h
3+
// ZHNetWorking
4+
//
5+
// Created by autohome on 2017/9/15.
6+
// Copyright © 2017年 autohome. All rights reserved.
7+
//
8+
9+
#import <Foundation/Foundation.h>
10+
11+
@class ZHRequest;
12+
13+
@protocol ZHRequestDelegate <NSObject>
14+
15+
16+
@optional;
17+
- (void)requestWillStart;
18+
- (void)requestFinished:(ZHRequest *)request responseObj:(id)responseObj;
19+
- (void)requestFinished:(ZHRequest *)request responseStr:(NSString *)responseStr;
20+
- (void)requestFailed:(NSError *)error;
21+
22+
#pragma mark ---download request
23+
- (void)requestOfDownloadFinished:(ZHRequest *)request filepath:(NSURL *)filepath;
24+
- (void)requestOfDownloadFailed:(ZHRequest *)request filepath:(NSURL *)filepath error:(NSError *)error;
25+
26+
@end

‎ZHNetWorking/ZHRequestManager.m

+174-28
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,11 @@ - (void)addRequest:(ZHRequest *)request {
129129
}
130130
}
131131

132+
// 请求即将开始回调
133+
if ([request.delegate respondsToSelector:@selector(requestWillStart)]) {
134+
[request.delegate requestWillStart];
135+
}
136+
132137
[sessionTask resume];
133138

134139
Lock;
@@ -143,7 +148,24 @@ - (NSURLSessionTask *)sessionTask4Request:(ZHRequest *)request {
143148
NSDictionary *params = request.params;
144149
NSURLSessionTask *task = nil;
145150
NSError *error = nil;
146-
task = [self dataTask4Request:request requestSerializer:requestSerializer urlStr:urlStr params:params constructingBlock:request.formData error:error];
151+
152+
NSString *method = @"GET";
153+
switch (request.requestType) {
154+
case ZHRequest_Type_GET:
155+
if (request.downloadPath) {
156+
return [self downloadTaskWithRequest:request downloadPath:request.downloadPath requestSerializer:requestSerializer url:request.urlString params:params downloadProcess:request.downloadProcess];
157+
} else {
158+
method = @"GET";
159+
}
160+
break;
161+
case ZHRequest_Type_POST:
162+
method = @"POST";
163+
break;
164+
default:
165+
break;
166+
}
167+
168+
task = [self dataTask4Request:request method:method requestSerializer:requestSerializer urlStr:urlStr params:params constructingBlock:request.formData error:error];
147169

148170
return task;
149171
}
@@ -177,25 +199,16 @@ - (AFHTTPRequestSerializer *)requestSerializer4Request:(ZHRequest *)request {
177199

178200
}
179201

180-
- (NSURLSessionDataTask *)dataTask4Request:(ZHRequest *)request requestSerializer:(AFHTTPRequestSerializer *)serializer
181-
urlStr:(NSString *)url
182-
params:(id)params
183-
constructingBlock:(ConstructingFormDataBlock)formdata
184-
error:(NSError *)error {
202+
- (NSURLSessionDataTask *)dataTask4Request:(ZHRequest *)request
203+
method:(NSString *)method
204+
requestSerializer:(AFHTTPRequestSerializer *)serializer
205+
urlStr:(NSString *)url
206+
params:(id)params
207+
constructingBlock:(ConstructingFormDataBlock)formdata
208+
error:(NSError *)error {
185209

186210
NSMutableURLRequest *urlRequest = nil;
187-
NSString *method = @"GET";
188-
switch (request.requestType) {
189-
case ZHRequest_Type_GET:
190-
method = @"GET";
191-
break;
192-
case ZHRequest_Type_POST:
193-
method = @"POST";
194-
break;
195-
default:
196-
break;
197-
}
198-
211+
199212
if (formdata) {
200213
urlRequest = [serializer multipartFormRequestWithMethod:method URLString:url parameters:params constructingBodyWithBlock:formdata error:&error];
201214
} else {
@@ -210,6 +223,61 @@ - (NSURLSessionDataTask *)dataTask4Request:(ZHRequest *)request requestSerialize
210223
return dataTask;
211224
}
212225

226+
/*!
227+
@method
228+
@abstract 返回下载任务
229+
@discussion request 对应的request,传递responseObj 为fileurl,
230+
传递request 是为了给request中的各个属性赋值 如果 responseStr,responseData等。
231+
*/
232+
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(ZHRequest *)request
233+
downloadPath:(NSString *)path
234+
requestSerializer:(AFHTTPRequestSerializer *)requestSerializer
235+
url:(NSString *)url
236+
params:(NSDictionary *)params
237+
downloadProcess:(DownloadProcessBlock)process {
238+
// 添加请求参数
239+
NSMutableURLRequest *urlRequest = [requestSerializer requestWithMethod:@"GET" URLString:url parameters:params error:nil];
240+
241+
// 保证下载路径 是一个路径,而不是文件夹
242+
BOOL isDirectory = NO;
243+
if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDirectory]) {
244+
isDirectory = NO;
245+
}
246+
NSString *targetDownloadPath = nil;
247+
if (isDirectory) {
248+
NSString *fileName = [urlRequest.URL lastPathComponent];
249+
targetDownloadPath = [NSString pathWithComponents:@[path, fileName]];
250+
}
251+
252+
if ([[NSFileManager defaultManager] fileExistsAtPath:targetDownloadPath]) {
253+
// AFN use `moveItemAtURL` to move downloaded file to target path,
254+
// this method aborts the move attempt if a file already exist at the path.
255+
// So we remove the exist file before we start the download task.
256+
// https://github.com/AFNetworking/AFNetworking/issues/3775
257+
[[NSFileManager defaultManager] removeItemAtPath:targetDownloadPath error:nil];
258+
}
259+
260+
NSURL *resumeDataUrl = [self incompleteDownloadTempPathForDownloadPath:path];
261+
NSData *resumeData = [NSData dataWithContentsOfURL:resumeDataUrl];
262+
263+
BOOL isValid = [self validateResumeData:resumeData];
264+
265+
266+
if (resumeData && isValid) {
267+
return [self.manager downloadTaskWithResumeData:resumeData progress:process destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
268+
return [NSURL fileURLWithPath:targetDownloadPath isDirectory:NO];
269+
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
270+
[self handleResult:request urlResponse:response responseObj:filePath error:error];
271+
}];
272+
} else {
273+
return [self.manager downloadTaskWithRequest:urlRequest progress:process destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
274+
return [NSURL fileURLWithPath:targetDownloadPath isDirectory:NO];
275+
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
276+
[self handleResult:request urlResponse:response responseObj:filePath error:error];
277+
}];
278+
}
279+
280+
}
213281

214282
- (void)handleResult:(ZHRequest *)request urlResponse:(NSURLResponse *)response responseObj:(id)responseObj error:(NSError *)error {
215283

@@ -218,34 +286,66 @@ - (void)handleResult:(ZHRequest *)request urlResponse:(NSURLResponse *)response
218286
request.allHeaderFields = httpResponse.allHeaderFields;
219287

220288
request.responseObj = responseObj;
289+
290+
NSError *serializerError = nil;
291+
221292
if ([responseObj isKindOfClass:[NSData class]]) {
222-
request.responseObj = responseObj;
223-
NSError *serializerError = nil;
293+
request.responseData = responseObj;
294+
224295
switch (request.responseSerilalizerType) {
225296
case ZHRequest_ResponseSerilalizerType_JSON:
226297
request.responseObj = [self.jsonResponseSerializer responseObjectForResponse:response data:responseObj error:&serializerError];
227-
request.responseString = [[NSString alloc] initWithData:responseObj encoding:NSUTF8StringEncoding];
228298
break;
229299
case ZHRequest_ResponseSerilalizerType_HTTP:
230300
//
231301
request.responseObj = [self.httpResponseSerializer responseObjectForResponse:response data:responseObj error:&serializerError ];
232-
request.responseString = [[NSString alloc] initWithData:responseObj encoding:NSUTF8StringEncoding];
233302
break;
234303
case ZHRequest_ResponseSerilalizerType_XML:
235304
//
236305
break;
237306
default:
238307
break;
239308
}
309+
if ([responseObj isKindOfClass:[NSData class]]) {
310+
request.responseString = [[NSString alloc] initWithData:responseObj encoding:NSUTF8StringEncoding];
311+
} else if ([responseObj isKindOfClass:[NSURL class]]) { // 如果是下载任务
312+
request.responseString = [((NSURL *)responseObj) absoluteString];
313+
}
240314
}
241-
}
242-
243-
244-
245-
246-
247315

316+
317+
// TODO 返回结果校验
318+
BOOL isValidResponse = NO;
319+
if (request.statusCode <= 200 && request.statusCode <= 400) {
320+
isValidResponse = YES;
321+
}
322+
323+
BOOL isSuccess = NO;
324+
if (!error && !serializerError && isValidResponse) {
325+
isSuccess = YES;
326+
}
327+
328+
if (isSuccess) {
329+
/// 请求成功回调
330+
if ([request.delegate respondsToSelector:@selector(requestFinished:responseObj:)]) {
331+
[request.delegate requestFinished:request responseObj:request.responseObj];
332+
}
333+
if ([request.delegate respondsToSelector:@selector(requestFinished:responseStr:)]) {
334+
[request.delegate requestFinished:request responseStr:request.responseString];
335+
}
336+
} else {
337+
if ([request.delegate respondsToSelector:@selector(requestFailed:)]) {
338+
[request.delegate requestFailed:error];
339+
}
340+
}
341+
}
248342

343+
- (void)requestDidSuccessWithRequest:(ZHRequest *)request responseObj:(id)responseObj{
344+
345+
}
346+
- (void)requestDidFailedWithRequest:(ZHRequest *)request error:(NSError *)error {
347+
348+
}
249349

250350

251351
- (void)cancelRequest:(ZHRequest *)request {
@@ -273,4 +373,50 @@ - (void)cancelAllRequest {
273373
}
274374
}
275375

376+
377+
#pragma mark - Resumable Download
378+
379+
- (NSURL *)incompleteDownloadTempPathForDownloadPath:(NSString *)downloadPath {
380+
NSString *tempPath = [[self incompleteDownloadTempCacheFolder] stringByAppendingPathComponent:downloadPath];
381+
return [NSURL fileURLWithPath:tempPath];
382+
}
383+
384+
- (NSString *)incompleteDownloadTempCacheFolder {
385+
NSFileManager *fileManager = [NSFileManager new];
386+
static NSString *cacheFolder;
387+
388+
if (!cacheFolder) {
389+
NSString *cacheDir = NSTemporaryDirectory();
390+
cacheFolder = [cacheDir stringByAppendingPathComponent:@"incomplete"];
391+
}
392+
393+
NSError *error = nil;
394+
if(![fileManager createDirectoryAtPath:cacheFolder withIntermediateDirectories:YES attributes:nil error:&error]) {
395+
NSLog(@"Failed to create cache directory at %@", cacheFolder);
396+
cacheFolder = nil;
397+
}
398+
return cacheFolder;
399+
}
400+
401+
- (BOOL)validateResumeData:(NSData *)data {
402+
// From http://stackoverflow.com/a/22137510/3562486
403+
if (!data || [data length] < 1) return NO;
404+
405+
NSError *error;
406+
NSDictionary *resumeDictionary = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:NULL error:&error];
407+
if (!resumeDictionary || error) return NO;
408+
409+
// Before iOS 9 & Mac OS X 10.11
410+
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED < 90000)\
411+
|| (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED < 101100)
412+
NSString *localFilePath = [resumeDictionary objectForKey:@"NSURLSessionResumeInfoLocalPath"];
413+
if ([localFilePath length] < 1) return NO;
414+
return [[NSFileManager defaultManager] fileExistsAtPath:localFilePath];
415+
#endif
416+
// After iOS 9 we can not actually detects if the cache file exists. This plist file has a somehow
417+
// complicated structue. Besides, the plist structure is different between iOS 9 and iOS 10.
418+
// We can only assume that the plist being successfully parsed means the resume data is valid.
419+
return YES;
420+
}
421+
276422
@end

‎user_growth_gift@2x.png

5.27 KB
Loading

‎user_growth_gift@3x.png

8.91 KB
Loading

0 commit comments

Comments
 (0)
Please sign in to comment.