未解决的错误(无法下标类型'[NSObject:AnyObject]'的值,其索引类型为'String')

时间:2018-06-13 02:30:08

标签: swift

我遇到了将编译器语言从2.3更新到3.3而在下图中出错的问题

enter image description here

如果有人可以帮助我,我会感谢他,因为我被困这个错误好几个月

代码:

导入UIKit 导入Firebase 导入GoogleMobileAds

类ViewController:UIViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {

@IBOutlet weak var BannerViewT: GADBannerView!
@IBOutlet weak var BannerViewo: GADBannerView!
@IBOutlet weak var BannerView: GADBannerView!
@IBOutlet weak var tblVideos: UITableView!

@IBOutlet weak var segDisplayedContent: UISegmentedControl!

@IBOutlet weak var viewWait: UIView!

@IBOutlet weak var txtSearch: UITextField!



 var Interstitial9:GADInterstitial!

var apiKey = "AIzaSyDLBKR3sQVNYzZ3jJvG3kUnoTyjEuQ9P9g" // Youtube 

var desiredChannelsArray = [String]()

var channelIndex = 0

var channelsDataArray: Array<Dictionary<NSObject, AnyObject>> = []

var videosArray: Array<Dictionary<NSObject, AnyObject>> = []
    var selectedVideoIndex: Int!


override func viewDidLoad() {
    super.viewDidLoad()



    self.BannerView.adUnitID = "ca-app-pub-7397080206102185/7252405968" // Thw one with cells
    self.BannerViewo.adUnitID = "ca-app-pub-7397080206102185/9312712656" // The one at the buttom
     self.BannerViewT.adUnitID = "ca-app-pub-7397080206102185/6262757920" // The one at the top

    self.BannerView.rootViewController = self
    self.BannerViewo.rootViewController = self
    self.BannerViewT.rootViewController = self

    let request: GADRequest = GADRequest()

    self.BannerView.load(request)
    self.BannerViewo.load(request)
    self.BannerViewT.load(request)


    Interstitial9 = GADInterstitial(adUnitID: "ca-app-pub-7397080206102185/4818446953")
    let req = GADRequest()
    Interstitial9.load(req)



    tblVideos.delegate = self
    tblVideos.dataSource = self


    getChannelDetails(useChannelIDParam: false)
}







override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


 func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "idSeguePlayer" {
        let playerViewController = segue.destination as! PlayerViewController
        playerViewController.videoID = videosArray[selectedVideoIndex]["videoID"] as! String



    }
}



// MARK: IBAction method implementation

@IBAction func changeContent(sender: AnyObject) {
    tblVideos.reloadSections(NSIndexSet(index: 0) as IndexSet, with: UITableViewRowAnimation.fade)
}


// MARK: UITableView method implementation

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if segDisplayedContent.selectedSegmentIndex == 0 {
        return channelsDataArray.count
    }
    else {
        return videosArray.count
    }
}


@IBAction func adshow(sender: AnyObject) {
    if (Interstitial9.isReady) {
        Interstitial9.present(fromRootViewController: self)

    }
}




func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell: UITableViewCell!

    if segDisplayedContent.selectedSegmentIndex == 0 {
        cell = tableView.dequeueReusableCell(withIdentifier: "idCellChannel", for: indexPath as IndexPath) 

        let channelTitleLabel = cell.viewWithTag(10) as! UILabel

        let channelDescriptionLabel = cell.viewWithTag(11) as! UILabel


        let thumbnailImageView = cell.viewWithTag(12) as! UIImageView

        let channelDetails = channelsDataArray[indexPath.row]
        channelTitleLabel.text = (channelDetails["title"] as! String)
        channelDescriptionLabel.text = channelDetails["description"] as? String
        thumbnailImageView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: (channelDetails["thumbnail"] as? String))!)!)!
    }
    else {
        cell = tableView.dequeueReusableCell(withIdentifier: "idCellVideo", for: indexPath as IndexPath) 

        let videoTitle = cell.viewWithTag(10) as! UILabel
        let videoThumbnail = cell.viewWithTag(11) as! UIImageView

        let videoDetails = videosArray[indexPath.row]
        videoTitle.text = videoDetails["title"] as? String
        videoThumbnail.image = UIImage(data: NSData(contentsOfURL: NSURL(string: (videoDetails["thumbnail"] as? String)!)!)!)
    }

    return cell
}


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 140.0
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if segDisplayedContent.selectedSegmentIndex == 0 {
        // In this case the channels are the displayed content.
        // The videos of the selected channel should be fetched and displayed.

        // Switch the segmented control to "Videos".
        segDisplayedContent.selectedSegmentIndex = 1

        // Show the activity indicator.
        viewWait.isHidden = false

        // Remove all existing video details from the videosArray array.
        videosArray.removeAll(keepingCapacity: false)
        desiredChannelsArray.removeAll(keepingCapacity: false)



        // Fetch the video details for the tapped channel.
        getVideosForChannelAtIndex(index: indexPath.row)
    }
    else {
        selectedVideoIndex = indexPath.row
        performSegue(withIdentifier: "idSeguePlayer", sender: self)
    }
}




// MARK: Custom method implementation

func performGetRequest(targetURL: NSURL!, completion: @escaping (_ data: NSData?, _ HTTPStatusCode: Int, _ error: NSError?) -> Void) {
    let request = NSMutableURLRequest(url: targetURL as URL)
    request.httpMethod = "GET"

    let sessionConfiguration = URLSessionConfiguration.default

    let session = URLSession(configuration: sessionConfiguration)

    let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        DispatchQueue.async(execute:)(dispatch_get_main_queue(), { () -> Void in
            completion(data as! NSData, (response as! HTTPURLResponse).statusCode, error as! NSError)
        })
    })


    task.resume()
}

//func noInternet {

//}

func getChannelDetails(useChannelIDParam: Bool) {
    var urlString: String!
    if !useChannelIDParam {
        urlString = "https://www.googleapis.com/youtube/v3/channels?part=contentDetails,snippet&autoplay=1&maxResults=0&id=\(desiredChannelsArray[channelIndex])&key=\(apiKey)"
    }
    else {"https://www.googleapis.com/youtube/v3/channels?part=contentDetails,snippet&maxResults=0&forUsername=\(desiredChannelsArray[channelIndex])&key=\(apiKey)"
    }

    let targetURL = NSURL(string: urlString)

    performGetRequest(targetURL: targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
        if HTTPStatusCode == 200 && error == nil {
            // Convert the JSON data to a dictionary.
            let resultsDict = (try! JSONSerialization.jsonObject(with: data! as Data, options: [])) as! Dictionary<NSObject, AnyObject>

            // Get the first dictionary item from the returned items (usually there's just one item).
            let items: AnyObject! = resultsDict["items"] as AnyObject?fi
            let firstItemDict = (items as! Array<AnyObject>)[0] as! Dictionary<NSObject, AnyObject>

            // Get the snippet dictionary that contains the desired data.
            let snippetDict = firstItemDict["snippet"] as! Dictionary<NSObject, AnyObject>

            // Create a new dictionary to store only the values we care about.
            var desiredValuesDict: Dictionary<NSObject, AnyObject> = Dictionary<NSObject, AnyObject>()
            desiredValuesDict["title"] = snippetDict["title"]
            desiredValuesDict["description"] = snippetDict["description"]
            desiredValuesDict["thumbnail"] = ((snippetDict["thumbnails"] as! Dictionary<NSObject, AnyObject>)["default"] as! Dictionary<NSObject, AnyObject>)["url"]

            // Save the channel's uploaded videos playlist ID.
            desiredValuesDict["playlistID"] = ((firstItemDict["contentDetails"] as! Dictionary<NSObject, AnyObject>)["relatedPlaylists"] as! Dictionary<NSObject, AnyObject>)["uploads"]


            // Append the desiredValuesDict dictionary to the following array.
            self.channelsDataArray.append(desiredValuesDict)


            // Reload the tableview.
          self.tblVideos.reloadData()

            // Load the next channel data (if exist).
            self.channelIndex += 1
            if self.channelIndex < self.desiredChannelsArray.count {
                self.getChannelDetails(useChannelIDParam: useChannelIDParam)
            }
            else {
                self.viewWait.isHidden = true
            }
        }
        else {
            print("HTTP Status Code = \(HTTPStatusCode)")
            print("Error while loading channel details: \(String(describing: error))")
        }
    })
}


func getVideosForChannelAtIndex(index: Int!) {
    // Get the selected channel's playlistID value from the channelsDataArray array and use it for fetching the proper video playlst.
    let playlistID = channelsDataArray[index]["playlistID"] as! String

    // Form the request URL string.
    let urlString = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=\(playlistID)&key=\(apiKey)"

    // Create a NSURL object based on the above string.
    let targetURL = NSURL(string: urlString)

    // Fetch the playlist from Google.
    performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
        if HTTPStatusCode == 200 && error == nil {
            // Convert the JSON data into a dictionary.
            let resultsDict = (try! NSJSONSerialization.JSONObjectWithData(data!, options: [])) as! Dictionary<NSObject, AnyObject>

            // Get all playlist items ("items" array).
            let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>

            // Use a loop to go through all video items.
            for i in 0 ..< items.count {
                let playlistSnippetDict = (items[i] as Dictionary<NSObject, AnyObject>)["snippet"] as! Dictionary<NSObject, AnyObject>

                // Initialize a new dictionary and store the data of interest.
                var desiredPlaylistItemDataDict = Dictionary<NSObject, AnyObject>()

                desiredPlaylistItemDataDict["title"] = playlistSnippetDict["title"]
                desiredPlaylistItemDataDict["thumbnail"] = ((playlistSnippetDict["thumbnails"] as! Dictionary<NSObject, AnyObject>)["default"] as! Dictionary<NSObject, AnyObject>)["url"]
                desiredPlaylistItemDataDict["videoID"] = (playlistSnippetDict["resourceId"] as! Dictionary<NSObject, AnyObject>)["videoId"]

                // Append the desiredPlaylistItemDataDict dictionary to the videos array.
                self.videosArray.append(desiredPlaylistItemDataDict)

                // Reload the tableview.
                self.tblVideos.reloadData()
            }
        }
        else {
            print("HTTP Status Code = \(HTTPStatusCode)")
            print("Error while loading channel videos: \(error)")
        }

        // Hide the activity indicator.
        self.viewWait.hidden = true


    })
}

}

1 个答案:

答案 0 :(得分:-1)

例如: 让data =(channelsDataArray.object(at:indexPath.row)as AnyObject).value(forKey:“title”)为?串 lblTitle.text = data

 func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {

 let cell = tableView.dequeueReusableCell(withIdentifier: "playListCell") as! playListCell

        cell.lblPlayListName.text = (playlistArray.object(at: indexPath.row) as AnyObject).value(forKey: "name") as? String
        cell.lblCount.text = (playlistArray.object(at: indexPath.row) as AnyObject).value(forKey: "total_records") as? String

        cell.btnplaylist.tag = (indexPath as NSIndexPath).row

        return cell
    }