Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.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
Swift 未解决的错误(不能在';[NSObject:AnyObject]';类型的值下标一个';字符串';)_Swift - Fatal编程技术网

Swift 未解决的错误(不能在';[NSObject:AnyObject]';类型的值下标一个';字符串';)

Swift 未解决的错误(不能在';[NSObject:AnyObject]';类型的值下标一个';字符串';),swift,Swift,我在将编译器语言从2.3更新到3.3时遇到问题,下图中有错误 请如果有人能帮助我,我会感谢他,因为我被这个错误困扰了好几个月 守则: 导入UIKit 进口火基 进口谷歌手机 类ViewController:UIViewController、UITableViewDelegate、UITableViewDataSource、UITextFieldDelegate{ @IBOutlet weak var BannerViewT: GADBannerView! @IBOutlet weak var

我在将编译器语言从2.3更新到3.3时遇到问题,下图中有错误

请如果有人能帮助我,我会感谢他,因为我被这个错误困扰了好几个月

守则:

导入UIKit 进口火基 进口谷歌手机

类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


    })
}
@IBOutlet弱var bannerview:GADBannerView!
@IBVAR BannerViewo:GADBannerView!
@IBVAR BannerView:GADBannerView!
@IBVAR tblVideos:UITableView!
@IBOutlet弱var segDisplayedContent:UISegmentedControl!
@IBVAR视图等待:UIView!
@IBMOutlet弱var txtSearch:UITextField!
var Interstitial9:GADInterstitial!
var apiKey=“aizasydlbkr3sqvnyzz3jvg3kunotyjeuq9p9g”//Youtube
var desiredChannelsArray=[String]()
var channelIndex=0
var channelsDataArray:Array=[]
var videosArray:Array=[]
var selectedVideoIndex:Int!
重写func viewDidLoad(){
super.viewDidLoad()
self.BannerView.adUnitID=“ca-app-pub-7397080206102185/7252405968”//Thw一个带单元格的
self.BannerViewo.adUnitID=“ca-app-pub-7397080206102185/9312712656”//按钮处的那个
self.BannerViewT.adUnitID=“ca-app-pub-7397080206102185/6262757920”//顶部的那个
self.BannerView.rootViewController=self
self.BannerViewo.rootViewController=self
self.BannerViewT.rootViewController=self
let请求:GADRequest=GADRequest()
self.BannerView.load(请求)
自我BannerViewo.load(请求)
自加载(请求)
间质9=GAD间质(adUnitID:“ca-app-pub-7397080206102185/4818446953”)
let req=GADRequest()
间隙9.负载(要求)
tblVideos.delegate=self
tblVideos.dataSource=self
getChannelDetails(useChannelIDParam:false)
}
重写函数didReceiveMemoryWarning(){
超级。我收到了记忆警告()
//处置所有可以重新创建的资源。
}
func prepareforsgue(segue:UIStoryboardSegue,sender:AnyObject?){
如果segue.identifier==“idSeguePlayer”{
让playervewcontroller=segue.destination为!playervewcontroller
playervewcontroller.videoID=videosArray[selectedVideoIndex][“videoID”]as!字符串
}
}
//标记:iAction方法实现
@iAction func changeContent(发件人:AnyObject){
tblVideos.reloadSections(NSIndexSet(索引:0)作为IndexSet,带有:UITableViewRowAnimation.fade)
}
//MARK:UITableView方法实现
func numberOfSectionsInTableView(tableView:UITableView)->Int{
返回1
}
func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
如果segDisplayedContent.selectedSegmentIndex==0{
返回channelsDataArray.count
}
否则{
返回videosArray.count
}
}
@iAction func adshow(发送方:AnyObject){
如果(填隙9.isReady){
间隙9.存在(fromRootViewController:self)
}
}
func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
变量单元格:UITableViewCell!
如果segDisplayedContent.selectedSegmentIndex==0{
cell=tableView.dequeueReusableCell(标识符为:“idCellChannel”,for:indexath作为indexath)
让channelTitleLabel=cell.viewWithTag(10)作为!UILabel
让channelDescriptionLabel=cell.viewWithTag(11)为!UILabel
让thumbnailImageView=cell.viewWithTag(12)为!UIImageView
让channelDetails=channelsDataArray[indexPath.row]
channelTitleLabel.text=(channelDetails[“title”]作为!字符串)
channelDescriptionLabel.text=channelDetails[“description”]作为?字符串
thumbnailImageView.image=UIImage(数据:NSData(内容URL:NSURL(字符串:(channelDetails[“缩略图”]as?字符串))!)!
}
否则{
cell=tableView.dequeueReusableCell(标识符为:“idCellVideo”,for:indexPath作为indexPath)
让videoTitle=cell.viewWithTag(10)作为!UILabel
让videoThumbnail=cell.viewWithTag(11)为!UIImageView
让videoDetails=videosArray[indexPath.row]
videoTitle.text=videoDetails[“title”]作为?字符串
video缩略图.image=UIImage(数据:NSData(内容URL:NSURL(字符串:(videoDetails[“缩略图”]as?字符串)!)!)
}
返回单元
}
func tableView(tableView:UITableView,heightForRowAt indexath:indexPath)->CGFloat{
返回140.0
}
func tableView(tableView:UITableView,didSelectRowAt indexPath:indexPath){
如果segDisplayedContent.selectedSegmentIndex==0{
//在这种情况下,频道是显示的内容。
//应获取并显示所选频道的视频。
//将分段控件切换到“视频”。
segDisplayedContent.selectedSegmentIndex=1
//显示活动指示器。
viewWait.ishiden=false
//从videosArray阵列中删除所有现有视频详细信息。
videosArray.removeAll(保留容量:false)
desiredChannelsArray.removeAll(保留容量:false)
//获取所选频道的视频详细信息。
GetVideosForchannelatidex(索引:indexPath.row)
}
否则{
selectedVideoIndex=indexPath.row
performsgue(带有标识符:“idSeguePlayer”,发件人:self)
}
}
//标记:自定义方法实现
func performGetRequest(targetURL:NSURL!,完成:@escaping(\uData:NSData?,\uHttpStatusCode:Int,\uError:NSError?->Void){
let request=NSMutableURLRequest(url:targetURL作为url)
request.httpMethod=“GET”
让sessionConfiguration=URLSessionConfiguration.default
let session=URLSession(配置:sessionConfiguration)
让task=session.dataTask(其中:request作为URLRequest,completionHandler:{(data,