如何使用NSURLConnection?

时间:2016-01-22 21:34:47

标签: ios nsurlconnection xcode7

请查看以下代码:

override func viewDidLoad() {
  super.viewDidLoad()

  let url2 = NSURL (string: "http://leinelab.net/api/spaceapi.json")
  let requestObj = NSURLRequest(URL: url2!);
  let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil;
  let responseData = (try? NSURLConnection.sendSynchronousRequest(requestObj, returningResponse: response)) as NSData?

  let datastring = NSString(data: responseData!, encoding: NSUTF8StringEncoding)  
  let datastring2 = String(datastring!)

  let text = ":true}"
  if datastring2.rangeOfString(text) != nil
  .
  .
  .

在这里,我必须与NSURLConnection合作才能访问带有自签名证书的网站,但我不知道如何。代码在Xcode 6下工作,在升级到Xcode 7后,它没有。

修改

这是错误消息:

2016-01-22 22:45:56.678 LL-Test[3968:147205] App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file. fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

1 个答案:

答案 0 :(得分:2)

自iOS 9起必须使用HTTPS。如果要使用HTTP,则必须在info.plist中配置例外。 由于此行为,datastringdatastring2nil,导致崩溃。

要配置&#34; App Transport Security&#34; -exceptions,请阅读Apple开发者论坛中的这篇文章:https://forums.developer.apple.com/thread/3544