TableView没有更新

时间:2016-06-17 20:10:25

标签: xcode swift calendar tableview

我正在努力让我的TableView在之后更新我完成了在viewDidLoad和viewDidAppear中调用的一些函数。我尝试在viewDidLoad的末尾使用self.tableView.reloadData(),但它没有工作,重新加载选项卡后,应用程序将崩溃。

以下是我的一些代码(我正在尝试从Google日历中获取事件并将其显示在TableView中)。我正在尝试显示一个名为listOfEvents的字符串数组,并且在已经加载了tableView之后,它正在填充

我还尝试在fetchEvents()的末尾添加self.tableView.reloadData()但是在重新加载选项卡时它也杀了我的app

class CalendarViewController: UITableViewController {

var listOfEvents: [String] = []

private let kKeychainItemName = "Google Calendar API"
private let kClientID = "clientID"

// If modifying these scopes, delete your previously saved credentials by
// resetting the iOS simulator or uninstall the app.
private let scopes = [kGTLAuthScopeCalendarReadonly]

private let service = GTLServiceCalendar()
let output = UITextView()

// When the view loads, create necessary subviews
// and initialize the Google Calendar API service
override func viewDidLoad() {
    super.viewDidLoad()

    if let auth = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychainForName(
        kKeychainItemName,
        clientID: kClientID,
        clientSecret: nil) {
            service.authorizer = auth
    }
}

// When the view appears, ensure that the Google Calendar API service is authorized
// and perform API calls
override func viewDidAppear(animated: Bool) {
    if let authorizer = service.authorizer,
        canAuth = authorizer.canAuthorize where canAuth {
            fetchEvents()
    } else {
        presentViewController(
            createAuthController(),
            animated: true,
            completion: nil
        )
    }
}

// Construct a query and get a list of upcoming events from the user calendar
func fetchEvents() {
    let query = GTLQueryCalendar.queryForEventsListWithCalendarId("primary")
    query.maxResults = 10
    query.timeMin = GTLDateTime(date: NSDate(), timeZone: NSTimeZone.localTimeZone())
    query.singleEvents = true
    query.orderBy = kGTLCalendarOrderByStartTime
    service.executeQuery(
        query,
        delegate: self,
        didFinishSelector: "displayResultWithTicket:finishedWithObject:error:"
    )
}

// Display the start dates and event summaries in the UITextView
func displayResultWithTicket(
    ticket: GTLServiceTicket,
    finishedWithObject response : GTLCalendarEvents,
    error : NSError?) {

        if let error = error {
            showAlert("Error", message: error.localizedDescription)
            return
        }

        var eventString = ""

        if let events = response.items() where !events.isEmpty {
            for event in events as! [GTLCalendarEvent] {
                let start : GTLDateTime! = event.start.dateTime ?? event.start.date
                let startString = NSDateFormatter.localizedStringFromDate(
                    start.date,
                    dateStyle: .ShortStyle,
                    timeStyle: .ShortStyle
                )
                eventString += "\(startString) - \(event.summary)\n"

                // An array holding all my upcoming events
                listOfEvents.append("\(startString) - \(event.summary)")
                print(listOfEvents)
            }
        } else {
            eventString = "No upcoming events found."
        }
        output.text = eventString
        self.tableView.reloadData()
}


// Creates the auth controller for authorizing access to Google Calendar API
private func createAuthController() -> GTMOAuth2ViewControllerTouch {
    let scopeString = scopes.joinWithSeparator(" ")
    return GTMOAuth2ViewControllerTouch(
        scope: scopeString,
        clientID: kClientID,
        clientSecret: nil,
        keychainItemName: kKeychainItemName,
        delegate: self,
        finishedSelector: "viewController:finishedWithAuth:error:"
    )
}

// Handle completion of the authorization process, and update the Google Calendar API
// with the new credentials.
func viewController(vc : UIViewController,
    finishedWithAuth authResult : GTMOAuth2Authentication, error : NSError?) {

        if let error = error {
            service.authorizer = nil
            showAlert("Authentication Error", message: error.localizedDescription)
            return
        }

        service.authorizer = authResult
        dismissViewControllerAnimated(true, completion: nil)
}

// Helper for showing an alert
func showAlert(title : String, message: String) {
    let alert = UIAlertController(
        title: title,
        message: message,
        preferredStyle: UIAlertControllerStyle.Alert
    )
    let ok = UIAlertAction(
        title: "OK",
        style: UIAlertActionStyle.Default,
        handler: nil
    )
    alert.addAction(ok)
    presentViewController(alert, animated: true, completion: nil)
}

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

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print(self.listOfEvents.count)
    return self.listOfEvents.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("Events Cell", forIndexPath: indexPath) as UITableViewCell

    var event = ""
    event = listOfEvents[indexPath.row]

    cell.textLabel?.text = event

    return cell
}

}

我将非常感谢任何帮助和见解:-)非常感谢!

1 个答案:

答案 0 :(得分:0)

在output.text = eventString之后,你应该重新加载tableview。