所以,我遇到的问题是" NSURLSession / NSURLConnection HTTP加载失败(kCFStreamErrorDomainSSL,-9802)"尝试访问API时,我的Swift代码中出错。但是,当我尝试使用带有NSAppTransportSecurity的info.plist中的常见变通方法时,我得到了" EXC_BAD_INSTRUCTION(代码= EXC_i386_INVOP,子代码= 0x0)"。下面是我的代码,我不能为我的生活弄清楚这里发生了什么。这里的任何帮助将不胜感激。
func getMoviesNowPlayingData(page:Int, completion: (dict: [String:Any]) -> ()) {
let urlString : String = "https://api.themoviedb.org/3/movie/now_playing?api_key=ebea8cfca72fdff8d2624ad7bbf78e4c&page=\(page)"
let escapedUrlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
let apiURL = NSURL(string:escapedUrlString!)
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(apiURL!, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) in
//NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802) occurs here
do {
if let data2 = data {
let jsonDict = try NSJSONSerialization.JSONObjectWithData(data2, options: NSJSONReadingOptions.MutableContainers) as! [String:Any]
//EXC_BAD_INSTRUCTION (code=EXC_i386_INVOP, subcode=0x0) crash occurs here
completion(dict: jsonDict)
}
} catch {
//handle NSError
print("error")
}
}).resume()
}
答案 0 :(得分:2)
问题在于说:
let jsonDict = try NSJSONSerialization.JSONObjectWithData(data2, options: NSJSONReadingOptions.MutableContainers) as! [String:Any]
强制演员,as!
失败。如果可以的话,我会劝阻使用强制演员。但是,至于它失败的原因,JSON包含类类型,所以你应该使用AnyObject
,而不是Any
,例如:
guard let jsonDict = try NSJSONSerialization.JSONObjectWithData(data2, options: []) as? [String: AnyObject] else {
print("not a dictionary")
return
}
// use `jsonDict` here
在上面的评论中,您建议在尝试将其投射到NSDictionary
时失败。我建议你再试一次,因为如果JSON是一个字典,返回的对象是一个NSDictionary
,所以演员不会失败。我怀疑你尝试的时候还有其他一些问题。