繁体   English   中英

委托方法未触发

[英]Delegate method not firing

我有一个协议和委托来获取 JSON 数据并将其传递回以前的视图控制器到某些文本字段。 我认为这是正确的,但委托方法没有在 AddBookViewController 上触发。 没有故事板,这一切都是以编程方式/使用笔尖完成的。

任何帮助将不胜感激,非常感谢。

导入 ISBN 视图控制器

import UIKit

protocol BookInfoReceived {
    func sendBookInfo(author: String, title: String)
}

class ImportISBNViewController: UIViewController {

    var session: NSURLSession!
    var lookUpID:String = ""  //0586057242
    var a: String = ""
    var t: String = ""
    var delegate: BookInfoReceived?

    @IBOutlet weak var isbnNumber: UITextField!

    init () {
        super.init(nibName:"ImportISBNViewController", bundle: nil)
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil)
    }

    required init (coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

    }

    func importISBN(sender: AnyObject) {

        lookUpID = isbnNumber.text!
        println("Pressed Import. ISBN: \(lookUpID)")
        fetchItem()
    }

    func fetchItem() {

        let requestURL = ("https://openlibrary.org/api/books?bibkeys=" + lookUpID + "&f&jscmd=data&format=json")
        if let url = NSURL(string: requestURL) {
            let req = NSURLRequest(URL: url)

            let dataTask = session.dataTaskWithRequest(req) {
                (data, response, error) in
                if data != nil {
                    var error: NSError?
                    if let jsonObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary  {

                        println("JSON Found: \(jsonObject.count)")

                        if jsonObject.count == 0  {
                            println("JSON URL has no data.")
                            //COMPUTER SAYS NO
                            self.showAlert()

                        } else {

                            if let bookInfoDictionary: AnyObject = jsonObject["\(self.lookUpID)"]{

                                //Retrieve the author name.
                                var names = [String]()
                                if let authors = bookInfoDictionary["authors"] as? NSArray {
                                    for author in authors {
                                        if let author = author as? NSDictionary,
                                            let name = author["name"] as? String {
                                                names.append(name)
                                        }
                                    }
                                }

                                self.a = join(",", names)
                                self.t = (bookInfoDictionary["title"] as? String)!
                                println("JSON Done. Title: \(self.t) Author: \(self.a) ")

                                self.delegate?.sendBookInfo(self.a, title: self.t)
                                self.dismissViewControllerAnimated(true, completion: nil)


                            }

                        }
                    } else {
                        if let error = error {
                            println("Error parsing JSON: \(error)")
                        }
                    }
                } else {
                    println("Error fetching Item: \(error.localizedDescription)")
                }
            }
            dataTask.resume()
        }

    }
func showAlert () {
        let alert = UIAlertController(title: "ISBN not found", message: "The ISBN entered was not found, would you like to try another?", preferredStyle: .Alert)

        let okAction = UIAlertAction(title: "OK", style: .Default) {
            UIAlertAction in
            println("ALERT: OK Pressed")
            self.isbnNumber.text = ""
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .Default) {
            UIAlertAction in
            println("ALERT: Cancel Pressed")
            self.dismissImport(self)
        }

        NSOperationQueue.mainQueue().addOperationWithBlock {
            alert.addAction(okAction)
            alert.addAction(cancelAction)
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }


func dismissImport(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }

@IBAction func lookUpBook(sender: UIButton) {
        importISBN(self)
    }

@IBAction func cancelImport(sender: AnyObject) {
    dismissImport(self)
    }
}

添加BookViewController

import UIKit

class AddBookViewController: UIViewController, BookInfoReceived {

    @IBOutlet weak var bookTitle: UITextField!
    @IBOutlet weak var bookAuthor: UITextField!

    let bookStore: BookStore

    init (bookStore: BookStore) {
        self.bookStore = bookStore
        super.init(nibName: "AddBookViewController", bundle: nil)

        navigationItem.title = "Add New Book"

    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func sendBookInfo(author: String, title: String) {
        println("HELLO IT'S ME THE DELEGATE")
        bookTitle.text = title
        bookAuthor.text = author
    }

    @IBAction func importISBN(sender: UIButton) {

        let importVC = ImportISBNViewController()
        navigationController!.presentViewController(importVC, animated: true, completion: nil)
        }

    @IBAction func saveNewBook(sender: UIButton) {

        let author = self.bookAuthor.text!
        let title = self.bookTitle.text!
        println("Adding book: Author: \(author) Title: \(title)")

        bookStore.addBook(author, bookTitle: title)
        println("Book count: \(self.bookStore.allBooks.count)")
      }

}

缺少设置委托的行

@IBAction func importISBN(sender: UIButton) {

    let importVC = ImportISBNViewController()
    importVC.delegate = self
    navigationController!.presentViewController(importVC, animated: true, completion: nil)
  }

委托不会在 AddBookViewController 的任何实例上触发,因为您从未将 AddBookViewController 的任何实例设置为委托! 你的 ImportISBNViewController没有委托——所以什么都没有发生。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM