Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift错误:对成员的引用不明确';jsonObject(带有:选项:)_Ios_Swift_Nsurlsession_Nsjsonserialization_Json Serialization - Fatal编程技术网

Ios Swift错误:对成员的引用不明确';jsonObject(带有:选项:)

Ios Swift错误:对成员的引用不明确';jsonObject(带有:选项:),ios,swift,nsurlsession,nsjsonserialization,json-serialization,Ios,Swift,Nsurlsession,Nsjsonserialization,Json Serialization,我正试图通过GET请求将图像从服务器加载到我的iOS应用程序中。但是,它会报告错误: 对成员的jsonObject的引用不明确(带有:选项:) 有人能帮忙解决这个错误吗 import UIKit class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet var MyCollectionView: UICollectionView!

我正试图通过GET请求将图像从服务器加载到我的iOS应用程序中。但是,它会报告错误:

对成员的jsonObject的引用不明确(带有:选项:)

有人能帮忙解决这个错误吗

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()

    }

}
试试这个:

替换为您的代码

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")
    }
}

当试图从NSURLSession任务的
数据
参数解码JSON时,会发生这种情况

数据
数据?
可选。首先将其展开以避免错误

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()

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)
        }
    }

我确实换了它。它说条件绑定的sinitializer必须具有可选类型,而不是“[String:AnyObject]”不是全部,而是仅受影响的部分,以便我可以检查……因为这在我的项目中起作用,所以我已经编辑了代码。请检查并告诉@KKRocksdid您将此数组放入do块中?如果让parseJSONArray=jsonArray as,请尝试强制转换?[字符串:AnyObject]{