Mohamed Elloumi Mohamed Elloumi - 1 year ago 52
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()


label.text = receivedString

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

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

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

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


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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download