在我的iOS应用程序中,我NSURLSessionTask用来将json数据下载到我的应用程序.我发现当我直接从浏览器调用url时,我得到了一个最新的json,当它从应用程序中调用时,我得到了json的旧版本.
这是由于缓存?如何判断NSURLSessionTask不使用缓存.
这是我使用的电话:
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
Run Code Online (Sandbox Code Playgroud)
谢谢!
在最新的苹果中引入新NSURLSession的替换NSURLConnection,所以在有不同的任务,那么有什么区别NSURLSessionDataTask,NSURLSessionDownloadTask?
以及在哪种情况下使用NSURLSessionTask和在哪里NSURLSessionDownloadTask?
objective-c ios nsurlsession nsurlsessiondownloadtask nsurlsessiontask
我想知道如何使用NSURLSession"单元测试"HTTP请求和响应.现在,当作为单元测试运行时,我的完成块代码不会被调用.但是,当从AppDelegate(didFinishWithLaunchingOptions)中执行相同的代码时,将调用完成块内的代码.正如在这个线程中所建议的那样,NSURLSessionDataTask dataTaskWithURL完成处理程序没有被调用,需要使用信号量和/或dispatch_group"以确保在网络请求完成之前阻塞主线程".
我的HTTP邮政编码如下所示.
@interface LoginPost : NSObject
- (void) post;
@end
@implementation LoginPost
- (void) post
{
NSURLSessionConfiguration* conf = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession* session = [NSURLSession sessionWithConfiguration:conf delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURL* url = [NSURL URLWithString:@"http://www.example.com/login"];
NSString* params = @"username=test@xyz.com&password=test";
NSMutableRequest* request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response:%@ %@\n", response, error); //code here never gets called in unit tests, break point here …Run Code Online (Sandbox Code Playgroud) 我现在开始使用NSURLSession,NSURLConnection因为它是Apple提供的一种新的优雅API.以前,我曾经NSURLRequest在GCD块中调用来在后台执行它.以下是我过去的做法:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:@"www.stackoverflow.com"]];
NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (error) {
// handle error
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
// do something with the data
});
});
Run Code Online (Sandbox Code Playgroud)
现在,我的使用方法NSURLSession如下:
- (void)viewDidLoad
{
[super viewDidLoad];
/*-----------------*
NSURLSession
*-----------------*/
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:
[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSDictionary *json …Run Code Online (Sandbox Code Playgroud) multithreading ios nsurlsession nsurlsessiontask nsurlsessiondatatask
使用AFNetworking 2.0时,我遇到了一些关于流媒体请求的挑战.
我想将大量文件(~50MB)上传到服务器,并且请求必须要流式传输.(否则app会因内存压力而崩溃)
我已尝试过各种方法在AFNetworking 2.0中做到这一点而没有任何成功.这就是我目前正在做的事情:
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:baseServiceUrl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
int imageIndex = 0;
for (NSURL *tempFileUrl in tempFilesUrlList) {
NSString* fileName = [NSString stringWithFormat:@"image%d", imageIndex];
NSError *appendError = nil;
[formData appendPartWithFileURL:tempFileUrl name:fileName error:&appendError];
imageIndex++;
}
} error:&error];
AFHTTPRequestOperation *requestOperation = nil;
requestOperation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
DLog(@"Uploading files completed: %@\n %@", operation, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLog(@"Error: %@", error);
}];
[requestOperation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, …Run Code Online (Sandbox Code Playgroud) 最初我认为如果NSURLSessionDownloadTask成功完成 URLSession:downloadTask:didFinishDownloadingToURL:方法将被调用,如果由于某种原因失败 - URLSession:task:didCompleteWithError:.它在模拟器上按预期工作(对于一个下载任务只调用此方法中的一个)但在设备上情况并非如此:如果失败,这两个方法都被调用,URLSession:downloadTask:didFinishDownloadingToURL:是第一个.(这两种方法都在参数中传递相同的任务)
有什么我想念的吗?
objective-c ios nsurlsession nsurlsessiondownloadtask nsurlsessiontask
我正在开发一个总是在后台运行的BLE应用程序.它从BLE外设获取与健康相关的数据,并将数据实时上传到服务器.我使用的NSURLSession一起NSURLSessionUploadTask创建的使用[NSURLSession uploadTaskWithRequest:myRequest fromFile:fileURL]将数据发送到服务器.
现在,应用程序在后台运行4-5小时,但之后iOS会杀死应用程序.
这是崩溃日志.
Date/Time: 2014-04-02 19:32:11.694 -0700
OS Version: iOS 7.0.4 (11B554a)
Report Version: 104
Exception Type: 00000020
Exception Codes: 0x000000008badf00d
Highlighted Thread: 2
Application Specific Information:
MyApp[2548] has active assertions beyond permitted time:
{(
<BKProcessAssertion: 0x15d83310> identifier: Background Content Fetching (66) process: MyApp[2548] permittedBackgroundDuration: 30.000000 reason: backgroundContentFetching owner pid:33 preventSuspend preventThrottleDownUI preventIdleSleep preventSuspendOnSleep
)}
Elapsed total CPU time (seconds): 1.300 (user 1.300, system 0.000), 2% CPU
Elapsed application CPU time (seconds): …Run Code Online (Sandbox Code Playgroud) 我使用NSURLSessionTasks 并且试图监视我的一些 HTTP 请求需要多长时间,当实际NSURLSessionTask发出初始请求时我可以监视什么委托方法(或其他方法)?如果这是一个NSURLConnection内部,NSOperation我只会在启动请求时启动一个计时器,但我无法控制任务何时开始。
我在 crashlytics 上遇到以下崩溃,但无法在我的设备上重现
Fatal Exception: NSGenericException
Task created in a session that has been invalidated
Run Code Online (Sandbox Code Playgroud)
在下一行
NSURLSessionTask *task = [self.session uploadTaskWithRequest:request fromFile:filePathURL];
[task resume];
[self.session finishTasksAndInvalidate];
Run Code Online (Sandbox Code Playgroud)
我在委托方法中处理了会话失效
- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error {
// Crashlytics logging
[CrashlyticsKit setBoolValue:true forKey:@"URLSession_didBecomeInvalid"];
self.session = [self createNewSession];
}
- (NSURLSession *)CreateSession {
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:SERVER_URL];
if (@available(iOS 11.0, *)) {
sessionConfig.waitsForConnectivity = YES;
}
return [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
}
Run Code Online (Sandbox Code Playgroud)
上传新版本后,我仍然遇到相同的崩溃,并且didBecomeInvalidWithError根本没有“”处的 Crashlytics 日志!
知道如何解决这个崩溃吗?
在此示例中,我NSURLSessionDataTask以默认优先级启动100 ,但随后将最后一个设置为高优先级.然而它似乎完全没有效果,因为最后一个任务仍然最后运行.
NSURLSession *session = ...
NSURLRequest *request = ...
for (int i = 1; i<=100; i++) {
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%d", i);
}];
if (i == 100) {
dataTask.priority = NSURLSessionTaskPriorityHigh;
}
[dataTask resume];
}
Run Code Online (Sandbox Code Playgroud)
为什么具有高优先级的此任务在默认优先级的其他99之前运行?我希望在添加高优先级任务之前可能会开始执行一些早期任务,但不是全部.
我甚至尝试将HTTPMaximumConnectionsPerHost设置为1,没有任何区别.
在我看来AFURLSessionManager,在设置taskWillPerformHTTPRedirection块时,适当的地方是,但我不确定处理它的最佳方法.
目前,在我的AFHTTPSessionManager子类中,我正在为所有请求全局设置重定向块,我知道我可以通过返回nil来阻止重定向:
- (void)setupRedirectBlock {
[self setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest *(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request) {
return nil;
}];
}
Run Code Online (Sandbox Code Playgroud)
...但我只需要对特定任务执行此操作,并且似乎没有办法从任务本身获取此信息.
我想我正在寻找某种用户信息字典或者我可以用来设置一个标志告诉这个方法返回request或返回nil.目前,我似乎必须对客户端中的响应/请求URL进行字符串比较,因为它远离实际创建任务和路径的位置.
所以这就引出了一个问题,我是在与常规进行对抗,还是没有更好的方法来逐个任务地拦截AFNetworking 2.0重定向?
为什么NSURLSession在创建和恢复NSURLSessionTask后操作队列为空?
有没有办法判断NSURLSession是否有待处理的任务?
目标是等待多个任务完成,但这不起作用:
NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithStreamedRequest:request];
[uploadTask resume];
// this prints "0"
NSLog(self.session.delegateQueue.operationCount)
// this returns immediately instead of waiting for task to complete
[self.session.delegateQueue waitUntilAllOperationsAreFinished];
Run Code Online (Sandbox Code Playgroud) 我正在将我的项目迁移到AFNetworking 2.0.使用AFNetworking 1.0时,我编写了代码来记录控制台中的每个请求/响应.这是代码:
-(AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(AFHTTPRequestOperation *, id))success
failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
AFHTTPRequestOperation *operation =
[super HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject){
[self logOperation:operation];
success(operation, responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
failure(operation, error);
}];
return operation;
}
-(void)logOperation:(AFHTTPRequestOperation *)operation {
NSLog(@"Request URL-> %@\n\nRequest Body-> %@\n\nResponse [%d]\n%@\n%@\n\n\n",
operation.request.URL.absoluteString,
[[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding],
operation.response.statusCode, operation.response.allHeaderFields, operation.responseString);
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用AFNetworking 2.0做同样的事情,根据我的理解,这意味着使用NSURLSessionDataTask对象代替AFHTTPRequestOperation.这是我的镜头.
-(NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler {
NSURLSessionDataTask *task = [super dataTaskWithRequest:request completionHandler:^(NSURLResponse …Run Code Online (Sandbox Code Playgroud) nsurlsessiontask ×13
ios ×12
nsurlsession ×9
objective-c ×6
afnetworking ×1
caching ×1
ios7 ×1
networking ×1
nsurlrequest ×1
redirect ×1
xctest ×1