我有一个测试应用程序设置,即使用户在下载过程中切换应用程序,它也能成功从网络下载内容.太好了,现在我有后台下载了.现在我想添加缓存.没有必要让我多次下载图像,b/c系统设计,给定一个图像URL我可以告诉你该URL后面的内容永远不会改变.所以,现在我想使用Apple内置的内存/磁盘缓存来缓存下载的结果,我已经阅读了很多(而不是我在NSCachesDirectory中手动保存文件,然后在创建之前检查文件)请求,ick).在尝试得到缓存在此工作的代码顶部的工作,我添加以下代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
// Set app-wide shared cache (first number is megabyte value)
[NSURLCache setSharedURLCache:[[NSURLCache alloc] initWithMemoryCapacity:60 * 1024 * 1024
diskCapacity:200 * 1024 * 1024
diskPath:nil]];
return YES;
}
Run Code Online (Sandbox Code Playgroud)
当我创建会话时,我添加了两行NEW(URLCache和requestCachePolicy).
// Helper method to get a single session object
- (NSURLSession *)backgroundSession
{
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.example.apple-samplecode.SimpleBackgroundTransfer.BackgroundSession"];
configuration.URLCache = [NSURLCache sharedURLCache]; // NEW LINE …Run Code Online (Sandbox Code Playgroud) iphone nsurlcache ios nsurlsession nsurlsessionconfiguration
在最新的苹果中引入新NSURLSession的替换NSURLConnection,所以在有不同的任务,那么有什么区别NSURLSessionDataTask,NSURLSessionDownloadTask?
以及在哪种情况下使用NSURLSessionTask和在哪里NSURLSessionDownloadTask?
objective-c ios nsurlsession nsurlsessiondownloadtask nsurlsessiontask
我正在使用新的NSURLSession API并允许用户下载文件.我想尝试告诉我的NSURLSession要同时运行多少次下载,但我没有办法做到这一点.我想尽量避免自己管理下载任务,如果我可以告诉系统有多少允许,那会更好 - 这对于排队后台下载以及我的应用程序未运行时会更好.有没有办法做到这一点?
我想显示特定文件的文件下载进度(接收了多少字节).它适用于NSURLSessionDownloadTask.我的问题是我想用NSURLSessionDataTask实现相同的功能.
这是将文件接收到NSData并写入文档文件夹的代码:
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithURL:theRessourcesURL
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if(error == nil)
{
NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pathToDownloadTo = [NSString stringWithFormat:@"%@/%@", docsDir, Name];
NSLog(@"SIZE : %@",[NSByteCountFormatter stringFromByteCount:data.length countStyle:NSByteCountFormatterCountStyleFile]);
[data writeToFile:pathToDownloadTo options:NSDataWritingAtomic error:&error];
}
}];
[dataTask resume];
Run Code Online (Sandbox Code Playgroud)
我在写入或完成数据任务后收到文件大小(在收到文件后):
NSLog(@"SIZE : %@",[NSByteCountFormatter stringFromByteCount:data.length countStyle:NSByteCountFormatterCountStyleFile]);
但是我想显示它当前的字节接收状态,NSURLSessionDataTask可以实现吗?
ios nsurlsession nsurlsessionconfiguration nsurlsessiondownloadtask
我有一个NSURLSession调用dataTaskWithRequest以便以这种方式发送POST请求
func makeRequest(parameters: String, url:String){
var postData:NSData = parameters.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String(postData.length )
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var error:NSError?
//request.HTTPBody = NSJSONSerialization.dataWithJSONObject(postData, options: nil, error: &error)
request.HTTPBody = postData
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
println("Response:\(response)")
// Other stuff goes here
})
Run Code Online (Sandbox Code Playgroud)
响应等于:
<NSHTTPURLResponse: 0x7fcd205d0a00> { URL: http://XXX.XXX.XXX:0000/*** } { status code: 200, headers { …Run Code Online (Sandbox Code Playgroud) 我过去两年一直在使用RestKit,但最近我开始考虑从这些monolith框架过渡,因为它看起来真的有点过分.
这是我前进的优点:
I. 对象映射过程中RestKit的最大损失. 你能推荐你使用的独立库,它们表现出灵活和稳定吗?
II.我很伤心,我不需要功能齐全的存储,但我仍然需要在某些地方提供一些缓存支持.我听说NSURLCache在上一次操作系统发布中变得很有用.你有没有用它,策略是什么?当网络连接断开时,它是否返回缓存的API响应?
III.有人面临同样的问题吗?您应用了哪些解决方案?也许有人可以提供一些关于他或她在使用纯AFNetworking的多个应用程序中使用的架构的建议?
core-data nsurlcache restkit-0.20 afnetworking-2 nsurlsession
NSURLSession是比Apple的NSURLConnection新的网络SDK .第三个旧选择是CFNetwork.
这里的问题是找出它们之间最大的区别,以了解Apple为何会像这样发展.
谢谢
我想知道如何使用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,现在在用于创建会话的NSURLSessionConfiguration对象上有一个timeoutIntervalForRequest.
但NSURLRequest对象上仍有一个timeoutInterval,可用于在会话中创建NSURLSessionTask.
我的问题是,如果配置的timeoutIntervalForRequest设置为30,但NSURLRequest用于创建任务的timeoutInterval为60,实际使用哪个超时间隔?
制作串行队列的最佳做法是NSURLSessionTasks什么?
就我而言,我需要:
NSURLSessionDataTask)NSURLSessionDownloadTask)这是我到目前为止所拥有的:
session = [NSURLSession sharedSession];
//Download the JSON:
NSURLRequest *dataRequest = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *task =
[session dataTaskWithRequest:dataRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Figure out the URL of the file I want to download:
NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSURL *downloadURL = [NSURL urlWithString:[json objectForKey:@"download_url"]];
NSURLSessionDownloadTask *fileDownloadTask =
[session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:playlistURL]]
completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
NSLog(@"completed!");
}];
[fileDownloadTask resume];
}
];
Run Code Online (Sandbox Code Playgroud)
除了在另一个完成中写一个完成块看起来很乱的事实,我打电话时得到一个EXC_BAD_ACCESS错误 …
nsurlsession ×10
ios ×7
objective-c ×3
nsurlcache ×2
cfnetwork ×1
cocoa-touch ×1
cookies ×1
core-data ×1
ios7 ×1
ios8 ×1
iphone ×1
json ×1
restkit-0.20 ×1
setcookie ×1
swift ×1
timeout ×1
xctest ×1