2015-10-14 47 views
2

這是我的代碼:斯威夫特。爲什麼dataTaskWithRequest不會調用閉包?

let targetURL = NSURL(string: self.urlStringForRequestChannelDetails) 
     let request = NSMutableURLRequest(URL: targetURL!) 
     request.HTTPMethod = "GET" 
     let defSession = NSURLSession.sharedSession() 
     let task = defSession.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in 
          let HTTPStatusCode = (response as! NSHTTPURLResponse).statusCode 
          if HTTPStatusCode == 200 && error == nil { 
           var resultsDict = [NSObject:AnyObject]() 
           do { 
            resultsDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [NSObject:AnyObject] 
           } catch let caught as NSError { 
            print(caught.description) 
           } 
           let items = resultsDict["items"] as! [AnyObject] 
           let firstItemDict = items[0] as! [NSObject:AnyObject] 

           let snippetDict = firstItemDict["snippet"] as! [NSObject:AnyObject] 
           self.channelData["title"] = snippetDict["title"] 
           self.channelData["description"] = snippetDict["description"] 

           self.channelData["thumbnail"] = ((snippetDict["thumbnails"] as! [NSObject:AnyObject])["default"] as! [NSObject:AnyObject])["url"] 
           self.channelData["playlistId"] = ((firstItemDict["contentDetails"] as! [NSObject:AnyObject])["relatedPlaylists"] as! [NSObject:AnyObject])["uploads"] 
          } else { 
           print("HTTP Status Code = \(HTTPStatusCode)") 
           print("Error while loading channel details: \(error)") 
          } 

     }) 
     task.resume() 

我打不通brakepoint停止處理程序的執行,因爲沒有調用關閉。我做錯了什麼?


UPD#1:

import Foundation 

class YtDataManager { 
    static var shared_instance = YtDataManager() 



    let apiKey = "#################################" 
    let #########ChannelName = "#########" 
    var channelData = [NSObject:AnyObject]() 
    var videosArray = [[NSObject:AnyObject]]() 

    var playlistId: String { return self.channelData["playlistId"] as! String} 
    var urlStringForRequestChannelDetails: String { return String("https://www.googleapis.com/youtube/v3/channels?part=contentDetails,snippet&forUsername=\(self.#########ChannelName)&key=\(self.apiKey)") } 
    var urlStringForRequestChannelVideos: String { return String("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=\(self.playlistId)&key=\(self.apiKey)") } 


    func performGetRequest(targetURL: NSURL!, completion: (data: NSData?, HTTPStatusCode: Int, error: NSError?) -> Void) { 
    } 

    func get###ChannelDetails() { 
     let targetURL = NSURL(string: self.urlStringForRequestChannelDetails) 
     let request = NSMutableURLRequest(URL: targetURL!) 
     request.HTTPMethod = "GET" 
     let defSession = NSURLSession.sharedSession() 
     let task = defSession.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in 

          let HTTPStatusCode = (response as! NSHTTPURLResponse).statusCode 
          if HTTPStatusCode == 200 && error == nil { 
           var resultsDict = [NSObject:AnyObject]() 
           do { 
            resultsDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [NSObject:AnyObject] 
           } catch let caught as NSError { 
            print(caught.description) 
           } 
           let items = resultsDict["items"] as! [AnyObject] 
           let firstItemDict = items[0] as! [NSObject:AnyObject] 

           let snippetDict = firstItemDict["snippet"] as! [NSObject:AnyObject] 
           self.channelData["title"] = snippetDict["title"] 
           self.channelData["description"] = snippetDict["description"] 

           self.channelData["thumbnail"] = ((snippetDict["thumbnails"] as! [NSObject:AnyObject])["default"] as! [NSObject:AnyObject])["url"] 
           self.channelData["playlistId"] = ((firstItemDict["contentDetails"] as! [NSObject:AnyObject])["relatedPlaylists"] as! [NSObject:AnyObject])["uploads"] 
          } else { 
           print("HTTP Status Code = \(HTTPStatusCode)") 
           print("Error while loading channel details: \(error)") 
          } 

     }) 
     task.resume() 


    } 


    func getVideosFor###Channel() { 
     let targetURL = NSURL(fileURLWithPath: self.urlStringForRequestChannelVideos) 
     self.performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in 
      if HTTPStatusCode == 200 && error == nil { 
       var resultsDict = [NSObject:AnyObject]() 
       do { 
        resultsDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [NSObject:AnyObject] 
       } catch let caught as NSError { 
        print(caught.description) 
       } 
       let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>> 

       // Use a loop to go through all video items. 
       for var i=0; i<items.count; ++i { 
        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)") 
      } 
     }) 
    } 
} 

請不要介意有關空函數。由於我已經開始解決方法,我試圖讓代碼更加簡單。


UPD#2:

import UIKit 

class YtFeedViewController: UIViewController { 
@IBOutlet weak var menuButton:UIBarButtonItem! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    if self.revealViewController() != nil { 
     menuButton.target = self.revealViewController() 
     menuButton.action = "revealToggle:" 
     self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) 

     YtDataManager.shared_instance.get###ChannelDetails() 
     print(YtDataManager.shared_instance.channelData.count) //0! 
     YtDataManager.shared_instance.getVideosFor###Channel() 
    } 

    self.navigationItem.title = "YouTube feed" 
    // Do any additional setup after loading the view. 
} 

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

}

回答

0

其實它的作用。我只是複製並粘貼代碼,刪除自定義邏輯並運行它。

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let targetURL = NSURL(string: "https://google.com") 
     let request = NSMutableURLRequest(URL: targetURL!) 
     request.HTTPMethod = "GET" 
     let defSession = NSURLSession.sharedSession() 
     let task = defSession.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in 
      print(response) 

     }) 
     task.resume() 
    } 
} 

enter image description here

+0

你知道,我只是複製粘貼你的代碼,並再次得到了這樣的行爲。什麼不對? – drewpts

+1

@drewpts嘗試創建一個新的單頁應用程序並運行代碼。我認爲問題可能在其他地方 – Arsen

+0

是的,在單獨的單頁應用程序代碼完美。 – drewpts