Alamofire URL 请求 - 解包可选值时意外发现 nil

Posted

技术标签:

【中文标题】Alamofire URL 请求 - 解包可选值时意外发现 nil【英文标题】:Alamofire URL Request - unexpectedly found nil when unwrapping an Optional Value 【发布时间】:2015-08-13 03:41:52 【问题描述】:

所以我有一个 PageViewController 来管理各种 VC,其中包含一系列股票代码、价格等。

我使用 Alamofire 管理模型中的 API 调用。以下是模型及其问题的简短摘要:

struct Stock 
    var last: String?
    var companyName: String?
    var symbol: String?

    var dataFields: [[String : String]]


class SwiftStock 
  class func fetchStockForListOfSymbols(#symbols: Array<String>, completion:(stock: Stock) -> ()) 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) 

      var stockURL = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22\(symbols)%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json"

      request(.GET, stockURL)
        .responseJSON  (_, response, resultsJSON, _) in

          if response?.statusCode == 200 

            if let stockData = (((resultsJSON as! [String : AnyObject])["query"] as! [String : AnyObject])["results"] as! [String : AnyObject])["quote"] as? [String : AnyObject] 

              // lengthy creation, yeah
              var dataFields = [[String : String]]()

              dataFields.append(["Last" : stockData["LastTradePriceOnly"] as? String ?? "N/A"])
              dataFields.append(["Company" : stockData["Name"] as? String ?? "N/A"])
              dataFields.append(["Symbol" : stockData["Symbol"] as? String ?? "N/A"])

              let stock = Stock(
                last: dataFields[0].values.array[0],
                companyName: dataFields[1].values.array[0],
                symbol: dataFields[2].values.array[0],
                dataFields: dataFields
              )
              dispatch_async(dispatch_get_main_queue()) 
                completion(stock: stock)
              
            
          
      
    
  

在 Alamofire 的 URLRequest 期间解包 Optional 值时意外发现 nil。不知道我在哪里搞砸了。有什么建议吗?

PageViewController上的代码如下:

class PageViewController: UIPageViewController, UIPageViewControllerDataSource

  var symbols: Array<String> = ["CMG", "TSLA", "FB", "SHAK"]
  var prices = [""]

  var stock: Stock?

  override func viewDidLoad() 
    super.viewDidLoad()

    // Set the data source to itself
    dataSource = self

    // Create the first screen
    if let startingViewController = self.viewControllerAtIndex(0) 
      setViewControllers([startingViewController], direction: .Forward, animated: true, completion: nil)
    
  

  override func viewWillAppear(animated: Bool) 
    super.viewWillAppear(animated)
    updateUI()
  

  func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? 

    var index = (viewController as! MainViewController).index
    index++
    return self.viewControllerAtIndex(index)
  

  func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? 

    var index = (viewController as! MainViewController).index
    index--
    return self.viewControllerAtIndex(index)
  

  func viewControllerAtIndex(index: Int) -> MainViewController? 
    if index == NSNotFound || index < 0 || index >= self.symbols.count 
      return nil
    

    // Create a new view controller and pass suitable data.
    if let pageContentViewController = storyboard?.instantiateViewControllerWithIdentifier("PageContentViewController") as? MainViewController 
      pageContentViewController.symbol = symbols[index]
      pageContentViewController.price = prices[index]
      pageContentViewController.index = index
      pageContentViewController.pageCount = symbols.count

      return pageContentViewController
    
    return nil
  

  func updateUI() 

    SwiftStock.fetchStockForListOfSymbols(symbols: symbols)  (stock) -> () in

      self.prices = ["\(stock.last!)"]
    
   


【问题讨论】:

【参考方案1】:

你的url是错误的,如果你把url复制粘贴到浏览器中它应该返回json,但它却返回了这个


  error: 
  lang: "en-US",
description: "Query syntax error(s) [line 1:54 mismatched character  '(' expecting set null,line 1:65 mismatched character ' ' expecting '"']"


这是完整的代码,无需使用库来检索股票代码:

import UIKit

class ViewController: UIViewController 

    override func viewDidLoad() 
        super.viewDidLoad()
        let url = NSURL(string: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22CMG%22%2C%20%22TSLA%22%2C%20%22FB%22%2C%20%22SHAK%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json")
        let session = NSURLSession.sharedSession()



        let dataTask = session.dataTaskWithURL(url!)  (data, response, error) -> Void in
            if(error != nil)
                print("Something wrong")
            

            do
                let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                if let quote = jsonData["query"]?["results"] as? NSDictionary 
                    if let quoteArray = quote["quote"] as? NSArray 
                        for quoteItem in quoteArray 
                            print(quoteItem["symbol"] as! NSString)
                        
                    
                

             catch

            


        

        dataTask?.resume()
    





【讨论】:

以上是关于Alamofire URL 请求 - 解包可选值时意外发现 nil的主要内容,如果未能解决你的问题,请参考以下文章

强制解包可选导致过滤器中的崩溃

@IBInspectable 致命错误:在展开可选值时意外发现 nil

Alamofire,致命错误:在展开可选值时意外发现 nil

Alamofire:在展开可选值时意外发现 nil

Alamofire 平面错误:在展开可选值时意外发现 nil

使用 Alamofire 调用数据并在 Viewcontroller 上传入 customcell。错误:在展开可选值时意外发现 nil