Mohamed Elloumi Mohamed Elloumi - 1 month ago 5
Swift Question

Accessing array results outside function

I'm trying to send books data (author, title ... ) using google books api to a new view controller , I was able to recieve this data but i can"t send them to another views.

import UIKit
import Firebase
class HomeViewController: UIViewController {
var receivedString: String = ""

@IBOutlet weak var bookLabel: UILabel!
@IBOutlet weak var label: UILabel!
override func viewDidLoad()

{
super.viewDidLoad()

label.text = receivedString


}
@IBAction func Getdata(_ sender: AnyObject) {
getBookInfo(isbn: "9781451648546")
self.performSegue(withIdentifier: "AddBookSegue", sender:self)
}



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

func getBookInfo(isbn: String) {
guard let url = URL(string: "https://www.googleapis.com/books/v1/volumes?q=isbn:\(isbn)") else {
print("***********************************")
print("the url is not valid")
return
}
URLSession.shared.dataTask(with: url, completionHandler: {data, response, error -> Void in
guard error == nil else {
print(response)
print(error!.localizedDescription)
return
}
guard let data = data else {
print("no error but no data")
print("***********************************")
print(response)
return
}
guard let jsonResult = try? JSONSerialization.jsonObject(with: data, options: []) else {
print("the JSON is not valid")
return
}
if let arrayOfTitles = (jsonResult as AnyObject).value(forKeyPath: "items.volumeInfo.title") as? [String] {
print(arrayOfTitles)
print("***********************************")

self.bookLabel.text = "\(arrayOfTitles)"
}
if let arrayOfAuthors = (jsonResult as AnyObject).value(forKeyPath: "items.volumeInfo.authors") as? [[String]] {
print(arrayOfAuthors)
print("***********************************") }



}).resume()
}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "AddBookSegue") {
let secondVC: AddBookController = (segue.destination as? AddBookController)!
secondVC.bookTitle = (arrayOfTitles) }
}
}


Use of unresolved identifier arrayOfTitle on the prepare for segue function

Answer

The variable arrayOfTitles (like arrayOfAuthors) is visible only in the innermost scope in which it was declared, in this case meaning inside the closure handling the results of URLSession.shared.dataTask.

You could make it an optional property of the HomeViewController class, which would allow you to access from any method. However, in this case you have a more serious problem: the closure which sets arrayOfTitles is called only after the web request returns, which may be long after you have already performed the segue where you use the results.

One possible fix is to make AddBookViewController perform the request in its viewWillAppear, and pass the ISBN from the other view controller.

Comments