【问题标题】:unexpectedly found nil while unwrapping an Optional value on return返回时打开可选值时意外发现 nil
【发布时间】:2016-03-03 03:31:56
【问题描述】:

我正在调用 Url,它将在 get() 函数中为我提供 Json。 我正在从另一个类调用 get() 函数并尝试以数组格式返回 Json 的结果。但它在返回语句上显示 Found null 错误。当我尝试打印 Json 的值时,它会正确写入。 这是我的代码。

 func get() -> NSArray
        {
            let postEndpoint: String =  "Link_For_JSON_Data"
            let session = NSURLSession.sharedSession()
            let url = NSURL(string: postEndpoint)!
            var jsonArray : NSArray?
            var jsonArray1 : NSArray?

            session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
                // Make sure we get an OK response
                guard let realResponse = response as? NSHTTPURLResponse where
                    realResponse.statusCode == 200 else
                {
                        print("Not a 200 response")
                        return
                }

                // Read the JSON
                do
                {
                    if let contentString = NSString(data:data!, encoding: NSUTF8StringEncoding)
                    {
                        // Print what we got from the call
                        jsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
                        print("jsonArray here", jsonArray)
                        // Update the label

                        dispatch_async(dispatch_get_main_queue())
                            { () -> Void in
                            self.getDataFormREST(jsonArray!)
                            }

                    }
                }

                catch
                {
                    print("bad things happened")
                }

            }).resume()

       return jsonArray!
        }

     func getDataFormREST(resultArray: NSArray) //-> NSArray
        {
            //        let resultDictionary = resultArray[(searchDetails)!-1] as! NSDictionary
            testArray = resultArray
            print("TESTArray ON ",testArray)
    }

【问题讨论】:

标签: ios json swift rest


【解决方案1】:

您不能编写执行异步调用然后将结果作为函数结果返回的函数。这不是异步代码的工作方式。您的函数将异步 dataTaskWithURL 请求排队,然后在它甚至有机会发送请求之前返回,更不用说接收结果了。

您必须将 get() 函数重写为 void 函数(不返回结果),但需要一个完成块。然后,在数据任务的完成处理程序中,您从jsonArray 获取数据并调用get() 函数的完成块,将jsonArray 传递给它。

请参阅我在 Github 上发布的这个项目,它说明了我在说什么:

SwiftCompletionHandlers on Github

【讨论】:

  • 我有点困惑。你能告诉我如何使用这是我的代码@Duncan C
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多