有没有人已经尝试在不使用包含的(和酷的)GCDWebUploader的情况下为GET请求实现处理程序(POST方法的相同问题)?
我需要服务器在将文件上传到客户端http://local/download/filename.ext
响应 GET 请求。
我正在使请求符合代码"后台会话管理器"(可在此处获得:AFNetworking 2.0和后台传输),并且它被发送并触发了无忧无虑。
我得到的服务器端日志如下:
[DEBUG] Did start background task
[DEBUG] Connection received 248 bytes on socket 14
[DEBUG] Connection on socket 14 preflighting request "GET /download/file.ext with 248 bytes body
[DEBUG] Connection on socket 14 processing request "GET /download/file.ext" with 248 bytes body
[EXCEPTION] *** +[NSJSONSerialization dataWithJSONObject:options:error:]: value parameter is nil
[DEBUG] Did close connection on socket 14
我无法弄清楚如何设置处理程序,以便不关心从 JSON 解析不存在的查询。
[webServer addHandlerForMethod:@"GET" path:@"/download" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
__strong AppDelegate* strongSelf = weakSelf;
NSLog(@"request for download is %@", request);
return [strongSelf downloadFile:request];
}];
我删除了这段代码以使其工作:
/*
// Add a handler to respond to GET requests
[webServer addDefaultHandlerForMethod:@"GET"
requestClass:[GCDWebServerRequest class]
asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) {
__strong AppDelegate* strongSelf = weakSelf;
.....
*/
[webServer addHandlerForMethod:@"GET" path:@"/download" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
__strong AppDelegate* strongSelf = weakSelf;
NSLog(@"request for download is %@", request);
return [strongSelf downloadFile:request];
}];
注释掉了接管并无论如何都需要 JSON 数据包的默认处理程序。
更新
为了使用GCDWebServer和NSURLSessions(即使使用AFNetworking)实现后台文件传输,对我来说最好的方法是使用MatchBlock实例化GET处理程序,如下所示:
[webServer addHandlerWithMatchBlock:^GCDWebServerRequest *(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) {
if (![requestMethod isEqualToString:@"GET"]) {
return nil;
}
if (![urlPath hasPrefix:@"/download"]) {
return nil;
}
return [[GCDWebServerRequest alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery];
} processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
GCDWebServerResponse* response = nil;
NSString* filePath = [[weakSelf applicationDocumentsDirectory] stringByAppendingPathComponent:[[request.path stringByRemovingPercentEncoding]];
NSString* fileType = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:NULL] fileType];
if (fileType) {
if ([fileType isEqualToString:NSFileTypeRegular]) {
// always allow ranges in our requests
response = [GCDWebServerFileResponse responseWithFile:filePath byteRange:request.byteRange];
[response setValue:@"bytes" forAdditionalHeader:@"Accept-Ranges"];
}
}
if (response) {
response.cacheControlMaxAge = 360;
} else {
response = [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_NotFound];
}
return response;
}];