我想发送JSON一个URL(POST和GET).
NSMutableDictionary *JSONDict = [[NSMutableDictionary alloc] init];
[JSONDict setValue:"myValue" forKey:"myKey"];
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:nil];
Run Code Online (Sandbox Code Playgroud)
我当前的请求代码无效.
NSMutableURLRequest *requestData = [[NSMutableURLRequest alloc] init];
[requestData setURL:[NSURL URLWithString:@"http://fake.url/"];];
[requestData setHTTPMethod:@"POST"];
[requestData setValue:postLength forHTTPHeaderField:@"Content-Length"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[requestData setHTTPBody:postData];
Run Code Online (Sandbox Code Playgroud)
使用ASIHTTPRequest是不是一个容易回答.
我一直在浏览StackOverflow问题,试图找出我的代码出错的地方,但我似乎无法做到!我正在尝试将我的Swift 1.2项目转换为Swift 2.0,并且我的类遇到了下载JSON数据的问题.
我在void函数中不断收到错误Unexpected non-void返回值.
这是我正在使用的代码,有点截断;
...
class func fetchMinionData() -> [Minion] {
var myURL = "http://myurl/test.json"
let dataURL = NSURL(string: myURL)
let request = NSURLRequest(URL: dataURL!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
let minionJSON = JSON(data!)
var minions = [Minion]()
for (_, minionDictionary) in minionJSON {
minions.append(Minion(minionDetails: minionDictionary))
}
return minions
//THIS IS WHERE THE ERROR OCCURS
}).resume()
}
...
Run Code Online (Sandbox Code Playgroud)
也许我忽略了一些简单的事情,但我不确定为什么我的功能会被视为无效.任何想法都会非常感激!谢谢!
iOS 10将很快发布,因此值得测试应用程序与它的兼容性.在此类测试期间,我们发现我们的应用程序无法在iOS10上恢复后台下载.在以前的版本上运行良好的代码在模拟器和设备上都不适用于新版本.
我没有将我们的代码减少到最小的工作测试用例,而是在互联网上搜索NSUrlSession教程并测试它们.行为是相同的:恢复工作在iOS的previos版本,但在10日休息.
下载恢复.您可以查看iOS10之前版本的工作原理.
下载失败.在xcode控制台中,您可以看到:
2016-09-02 16:11:24.913 HalfTunes[35205:2279228] *** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL
2016-09-02 16:11:24.913 HalfTunes[35205:2279228] *** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL
2016-09-02 16:11:24.913 HalfTunes[35205:2279228] Invalid resume data for background download. Background downloads must use http or https and must download to an accessible file.
Run Code Online (Sandbox Code Playgroud)
如果您在下载文件时激活离线模式,则可以获得
Url session completed with error: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL} {
NSLocalizedDescription = "unsupported URL";
}
Run Code Online (Sandbox Code Playgroud)
当网络关闭时,下载永远不会在网络再次启动时恢复.暂停的其他用例(例如重新启动)也不起作用.
我试图使用建议的代码检查返回的resumeData是否有效 …
我有一个生产的应用程序以及具有自签名证书的开发服务器.
我正在尝试测试NSURLSession和后台下载,但似乎无法过去- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
当我使用时,NSURLConnection我可以使用以下方法绕过它:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
NSLog(@"canAuthenticateAgainstProtectionSpace %@", [protectionSpace authenticationMethod]);
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(@"didReceiveAuthenticationChallenge %@ %zd", [[challenge protectionSpace] authenticationMethod], (ssize_t) [challenge previousFailureCount]);
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何使用NSURLSession> :(
这是我目前的(不起作用):
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
NSLog(@"NSURLSession did receive challenge.");
completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}
Run Code Online (Sandbox Code Playgroud)
我还尝试创建一个类别NSURLSession …
我注意到实现NSURLSessionDataDelegate和启动任务偶尔会抛出一个EXC_BAD_ACCESS.给出错误的实际调用方法似乎有所不同,但总是来自CFNetwork.在大多数情况下,调用方法来自NSURLSession delegate_dataTask:didReceiveData:completionHandler.我在下面附上了两个不同来电的崩溃日志.我还附上了我的实施NSURLSessionDataDelegate.
不幸的是我无法可靠地重现错误,所以我没有一个示例脚本来共享.创建和启动Downloader对象最终会产生错误.对于较大的文件,它似乎经常发生.我在这里做错了吗?有没有一种好的方法从这个堆栈跟踪调试?
我已经在iOS10和10.1.1上测试了相同的结果.
执行:
class Downloader: NSObject, NSURLSessionDataDelegate {
private let url: String
var finished = false
let finishCondition = NSCondition()
init(url:String) {
self.url = url
super.init()
}
func start() {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config,
delegate: self,
delegateQueue: nil)
guard let u = NSURL(string: url) else {
return
}
let request = NSMutableURLRequest(URL: u)
let task = session.dataTaskWithRequest(request)
task.resume()
}
func URLSession(session: NSURLSession, dataTask: …Run Code Online (Sandbox Code Playgroud) 我有一个必须下载多个大文件的应用程序.我希望它按顺序逐个下载每个文件而不是同时下载.当它同时运行时,应用程序会过载并崩溃.
所以.我试图将downloadTaskWithURL包装在NSBlockOperation中,然后在队列上设置maxConcurrentOperationCount = 1.我在下面编写了这段代码,但由于两个文件同时下载,因此无法正常工作.
import UIKit
class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDownloadDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
processURLs()
}
func download(url: NSURL){
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
let downloadTask = session.downloadTaskWithURL(url)
downloadTask.resume()
}
func processURLs(){
//setup queue and set max conncurrent to 1
var queue = NSOperationQueue()
queue.name = "Download queue"
queue.maxConcurrentOperationCount = 1
let url = NSURL(string: "http://azspeastus.blob.core.windows.net/azurespeed/100MB.bin?sv=2014-02-14&sr=b&sig=%2FZNzdvvzwYO%2BQUbrLBQTalz%2F8zByvrUWD%2BDfLmkpZuQ%3D&se=2015-09-01T01%3A48%3A51Z&sp=r") …Run Code Online (Sandbox Code Playgroud) 我收到一个奇怪的错误:
致命异常:NSInvalidArgumentException*** - [_ NSXPCDistantObject methodSignatureForSelector:]:没有为名为com.apple.nsurlsessiond的服务的连接连接设置协议"
这个问题似乎只发生在iOS 9上.根据堆栈跟踪,错误是由调用触发的-[UIApplication _sendWillEnterForegroundCallbacks].
Thread : Fatal Exception: NSInvalidArgumentException
0 CoreFoundation 6485512008 __exceptionPreprocess
1 libobjc.A.dylib 6833323904 objc_exception_throw
2 CoreFoundation 6485511824 -[NSException initWithCoder:]
3 Foundation 6500536092 -[_NSXPCDistantObject methodSignatureForSelector:]
4 CoreFoundation 6485526892 ___forwarding___
5 CoreFoundation 6484495532 _CF_forwarding_prep_0
6 CoreFoundation 6485141004 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__
7 CoreFoundation 6485138988 _CFXRegistrationPost
8 CoreFoundation 6485138348 ___CFXNotificationPost_block_invoke
9 CoreFoundation 6485554212 -[_CFXNotificationRegistrar find:object:observer:enumerator:]
10 CoreFoundation 6484354836 _CFXNotificationPost
11 Foundation 6500543948 -[NSNotificationCenter postNotificationName:object:userInfo:]
12 UIKit 6577878356 -[UIApplication _sendWillEnterForegroundCallbacks]
continues ...
Run Code Online (Sandbox Code Playgroud)
所以看起来当应用程序进入前台时,一些观察者注册尝试nsurlsessiond通过RPC 重新连接并失败?我使用后台传输会话NSURLSession …
class PostFOrData {
let url = NSURL( string: "http://210.61.209.194:8088/SmarttvWebServiceTopmsoApi/GetReadlist")
var picUrl = NSURL(string : "http://210.61.209.194:8088/SmarttvMedia/img/epi00001.png")
var responseString : NSString = ""
func forData() -> NSString {
let request = NSMutableURLRequest( URL: url!)
request.HTTPMethod = "POST"
var s : NSString = ""
let postString : String = "uid=59"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
} else {
println("response = \(response!)")
self.responseString = NSString(data: data, encoding: NSUTF8StringEncoding)!
println("responseString = …Run Code Online (Sandbox Code Playgroud) 我使用iOS 9作为目标并使用Xcode 7.1,尝试将所有内容作为我所有ATS解决方案的最佳级别,但是没有用.以下是控制台上的以下错误说明.如果有任何建议,我将被迫.
这里的一些关键事项是 -
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
Error excluding Main.db from backup Error Domain=NSCocoaErrorDomain Code=4 "The file “Main.db” doesn’t exist." UserInfo={NSURL=file:///Users/Raj/Library/Developer/CoreSimulator/Devices/BC3A0589-3B9A-4AFD-8F2A-B1C92FA341DD/data/Containers/Data/Application/70B3043A-8553-41E5-A147-8508D08BF3E6/Documents/Main.db, NSFilePath=/Users/Raj/Library/Developer/CoreSimulator/Devices/BC3A0589-3B9A-4AFD-8F2A-B1C92FA341DD/data/Containers/Data/Application/70B3043A-8553-41E5-A147-8508D08BF3E6/Documents/Main.db, NSUnderlyingError=0x798465c0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
2016-08-30 21:09:10.867 GFIM[80653:484899] SFOAuthCredentials:revokeRefreshToken: refresh token revoked. Cleared identityUrl, instanceUrl, issuedAt fields
2016-08-30 21:09:10.871 GFIM[80653:484899] INFO|0|SFPasscodeManager|Resetting passcode upon logout.
SFOAuthCredentials:revokeRefreshToken: refresh token revoked. Cleared identityUrl, instanceUrl, issuedAt fields
Run Code Online (Sandbox Code Playgroud)
这些可能是问题的原因.
2016-08-30 21:09:19.095 GFIM[80653:484899] SFOAuthCoordinator:webViewDidStartLoad: host=test.salesforce.com : path=/
2016-08-30 21:09:19.863 GFIM[80653:484962] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813) …Run Code Online (Sandbox Code Playgroud) nsurlsession ×10
ios ×6
swift ×6
objective-c ×2
closures ×1
get ×1
http ×1
ios10 ×1
ios7 ×1
ios9 ×1
macos ×1
nsoperation ×1
nsrunloop ×1
post ×1
xcode ×1