我有一个协议&委托获取JSON数据并将其传递回上一个视图控制器到一些文本字段。我认为这是正确的,但委托方法不是在AddBookViewController上触发。没有故事板,它都以编程方式/与笔尖完成。
非常感谢任何帮助,非常感谢。
ImportISBNViewController
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)
}
}
AddBookViewController
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)")
}
}
答案 0 :(得分:2)
缺少设置代理的行
@IBAction func importISBN(sender: UIButton) {
let importVC = ImportISBNViewController()
importVC.delegate = self
navigationController!.presentViewController(importVC, animated: true, completion: nil)
}
答案 1 :(得分:1)
委托不会在AddBookViewController的任何实例上触发,因为您从未将AddBookViewController的任何实例设置为委托!你的ImportISBNViewController有 no 委托 - 所以没有任何反应。