【问题标题】:Swift Error: ambiguous reference to member 'jsonObject(with:options:)Swift 错误:对成员 'jsonObject(with:options:) 的模糊引用
【发布时间】:2017-07-21 10:34:22
【问题描述】:

我正在尝试借助 GET 请求将图像从服务器加载到我的 iOS 应用程序中。但是却报错:

对成员 'jsonObject(with:options:) 的模糊引用

谁能帮忙解决这个错误?

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet var MyCollectionView: UICollectionView!

    var images : [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        loadImages()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //MyCollectionViewCell

        let myCell:MyCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCollectionViewCell



        DispatchQueue.global(qos: .background).async{

            let imageString = self.images[indexPath.row]
            let imageUrl = NSURL(string: imageString)
            let imageData = NSData(contentsOf: imageUrl! as URL)

            DispatchQueue.main.async {
                //if(imageData! = nil)
                //{

                    myCell.myImageView.image = UIImage(data: imageData! as Data)

                //}//end of if
            }//end of DispatchQueue.main.async




        };//end of main dispatch

        return myCell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("User tapped on image # \(indexPath.row)")
    }

    func loadImages()
    {
            let startTime = NSDate.timeIntervalSinceReferenceDate

            var pageUrl = "Url is here"
        let myUrl = NSURL(string: pageUrl)
        let request = NSMutableURLRequest(url:myUrl! as URL)

        let task = URLSession.shared.dataTask(with: request as URLRequest){
                data, response, error in

            //If error displays any alert message
            if error != nil {

                var myAlert = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)

                let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)

                myAlert.addAction(okAction)

                self.present(myAlert, animated: true, completion: nil)

                return


            }

            var err: NSError?

            if let usabledata = data{
            do{
            var jsonArray = try JSONSerialization.jsonObject(with: usabledata, options: .mutableContainers) as! [String:AnyObject]
                print(jsonArray)

            //conditional binding error here
            if let parseJSONArray = jsonArray {

                self.images = parseJSONArray as! [String]

                DispatchQueue.main.async(execute: {
                    self.MyCollectionView.reloadData()

                })//end of dispatchQueue


            }//end of if
            }catch{
                print(error)

            }


        }
        }

        task.resume()

    }

}

【问题讨论】:

    标签: ios swift nsurlsession nsjsonserialization json-serialization


    【解决方案1】:

    试试这个:

    替换为您的代码

    if let usableData = data {
        do {
            var jsonArray = try JSONSerialization.jsonObject(with: usableData, options: .mutableContainers)  as! [String:AnyObject] 
            if let parseJSONArray = jsonArray as? [String] {
                // parse array here
            }    
        } catch {
            print("JSON Processing Failed")
        }
    }
    

    【讨论】:

    • 我确实替换了它。它说条件绑定的初始化器必须具有可选类型,而不是 '[String:AnyObject]'
    • 不是完整的,而是受影响的部分,所以我可以检查一下……因为这在我的项目中有效,所以
    • 我已经编辑了代码。请检查并告诉@KKRocks
    • 你把这个数组放在do块里了吗?
    • 尝试强制转换 if let parseJSONArray = jsonArray as? [字符串:AnyObject]{
    【解决方案2】:

    当尝试从 NSURLSession 任务的 data 参数解码 JSON 时会发生这种情况。

    dataData? 可选的。先拆开包装以免出错。

    nsURLSession.dataTask(with: url) { (data, response, error) in
    
        // unwrap `data: Data?` first
    
        guard let dictionary = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] else {
            return
        }
    }.resume()
    

    【讨论】:

      【解决方案3】:

      NSData 返回可选的,这就是为什么你需要使用条件可选绑定技术来解包它,然后它才会起作用。

          let content = NSData()
      
          if let data = content {
              do {
                  let json =  try JSONSerialization.jsonObject(with: data as Data, options: []) as! NSDictionary
              } catch let error {
                  print(error)
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-22
        • 2016-05-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多