我有一个应用程序使用一个backgroundSessionConfiguration实例NSURLSession来处理一些NSURLSessionDownloadTask任务.任务是正确创建的,并完成下载,但是URLSession:downloadTask:didFinishDownloadingToURL:当我将下载的文件从location磁盘上的永久位置移动时,我有时(读取:经常)得到错误:
NSUnderlyingError=0x178247890 "The operation couldn’t be completed. No such file or directory"
Run Code Online (Sandbox Code Playgroud)
就好像在我有机会移动它之前,下载的文件被清除了临时目录(../Library/Caches/com.apple.nsnetworkd/ ..).
对同一个远程文件运行操作将在所有其他因素相同的情况下两种方式运行,因此我无法识别任何会导致它有时工作的内容.
反正是为了确保这个文件能够长时间保持足够的状态,一旦完成就将其移动到位?
编辑:我也看到了正常(非背景)会话的频率
这是我的两个例子:
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = ["Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": UIDevice.currentDevice().model]
var request = NSMutableURLRequest(URL: NSURL(string: "http://XXX"))
request.HTTPMethod = "POST"
let valuesToSend = ["key":value, "key2":value]
var error: NSError?
let data = NSJSONSerialization.dataWithJSONObject(valuesToSend, options:NSJSONWritingOptions.PrettyPrinted, error: &error)
request.HTTPBody = data
if error == nil {
let task = NSURLSession(configuration: config).dataTaskWithRequest(request,
completionHandler: {data, response, error in
if error == nil {
println("received == \(NSString(data: data, encoding: NSUTF8StringEncoding))")
}
})
task.resume()
} else {
println("Oups error \(error)")
}
Run Code Online (Sandbox Code Playgroud)
和第二个
let config = …Run Code Online (Sandbox Code Playgroud) 我尝试NSURLSession在iOS 8中使用共享扩展程序上传图像,但在调用后立即出现此错误
[task resume]
Error Domain=NSURLErrorDomain Code=-995 "The operation couldn’t be completed. (NSURLErrorDomain error -995.)"
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:DEFAULT_SHARE_SESSION_ID];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:self.queue];
NSURLRequest *request = [self getMultipartUploadRequest:data url:url albumId:albumId];
// ... saving file here to Documents folder
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:url1];
[uploadTask resume];
Run Code Online (Sandbox Code Playgroud)
而且我在控制台中也有这条消息:
Attempted to create a task in a session that has been invalidated
Run Code Online (Sandbox Code Playgroud)
此代码绝对适用于应用程序,但在共享扩展程序中不起作用.我找不到代码-995的含义.
有任何想法吗?
展望了本文档NSURLSession和NSURLSessionConfiguration,我的印象是我应该像下面这样的字典进行配置下:
// Create a dictionary to describe the proxy
NSDictionary *proxyDict = @{
(NSString *)kCFProxyHostNameKey : @"myProxyHost.com",
(NSString *)kCFProxyPortNumberKey : @"12345",
(NSString *)kCFProxyTypeKey : (NSString*)kCFProxyTypeHTTP
};
// Create a configuration that uses the dictionary
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
[configuration setConnectionProxyDictionary:proxyDict];
Run Code Online (Sandbox Code Playgroud)
但是,NSURLSession使用此配置创建的请求将直接连接.
我正在尝试学习在Swift中使用API.作为一个很好的第一次测试,我想我已经点击itunes API并返回一些搜索结果.我在游乐场使用以下代码.我没有任何错误,但我的println没有输出任何东西.谁知道什么是错的?
谢谢!
import UIKit
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely()
let url = NSURL(string: "https://itunes.apple.com/lookup?id=909253")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
task.resume()
Run Code Online (Sandbox Code Playgroud) 我的代码执行GET请求,如下所示:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
// ...
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
if error != nil {
println("error = \(error)")
return
}
if let HTTPresponse = response as? NSHTTPURLResponse {
if HTTPresponse.statusCode == 200 { // Successfully got response
var err: NSError?
if let json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &err) as? [String : AnyObject] {
// Success decoding JSON
} else {
// Failed -> stop activity indicator
dispatch_async(dispatch_get_main_queue(), { …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
我更新我的Xcode时遇到3个错误
1- App Transport Security已阻止明文HTTP(http://)资源加载,因为它不安全.可以通过应用程序的Info.plist文件配置临时例外.
2- CFNetwork SSLHandshake失败(-9824)
3- NSURLSession/NSURLConnection HTTP加载失败(kCFStreamErrorDomainSSL,-9824)
我试过了:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourdomain.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>Run Code Online (Sandbox Code Playgroud)
和
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key><true/>
</dict>Run Code Online (Sandbox Code Playgroud)
但他们没有工作.任何人都可以帮助我!谢谢.
我正在尝试通过FTP将文件上传到服务器.根据 Apple文档, NSURLSession类支持FTP操作.
有一个着名的Apple开发者博客,也支持这一点.但是还不清楚NSURLSession API是否支持ftp上传?(我尝试了建议的方式并得到错误).
使用传统的CFFTPStreamRef方式 ,ftp上传工作正常,但在9.0中已弃用.标题说:CF_DEPRECATED(10_3,10_11,2_0,9_0,"对ftp请求使用NSURLSessionAPI")
任何想法,示例或链接,以获得帮助.我现在正在尝试这样的事情:
NSURL *url_upload = [NSURL URLWithString:@"ftp://username:password@thelink/myfolder/filename.zip"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url_upload];
[request setHTTPMethod:@"PUT"];
NSURL *docsDirURL = [NSURL fileURLWithPath:filePath];
NSURLProtectionSpace * protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:url_upload.host port:[url_upload.port integerValue] protocol:url_upload.scheme realm:nil authenticationMethod:nil];
NSURLCredential *cred = [NSURLCredential
credentialWithUser:userId
password:password
persistence:NSURLCredentialPersistenceForSession];
NSURLCredentialStorage * cred_storage ;
[cred_storage setCredential:cred forProtectionSpace:protectionSpace];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.URLCredentialStorage = cred_storage;
sessionConfig.timeoutIntervalForRequest = 30.0;
sessionConfig.timeoutIntervalForResource = 60.0;
sessionConfig.allowsCellularAccess = YES;
sessionConfig.HTTPMaximumConnectionsPerHost = 1;
NSURLSession *upLoadSession = …Run Code Online (Sandbox Code Playgroud) 我需要下载一个mp3文件,但我只需要歌曲的前20秒(如果歌曲少于20秒,则需要整首歌曲).
这就是我下载整首歌的方式:
func downloadSong(audioUrl: URL) {
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void in
guard let location = location, error == nil else { return }
do {
try FileManager.default.moveItem(at: location, to: destinationUrl)
// song available in destinationUrl
} catch let error as NSError {
}
}).resume()
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在20秒后停止下载?我知道我可以下载整首歌然后剪下来,但我想要更高效,特别是如果这首歌很长.