0

I have two swift files in my project. One is called loadApi.swift and the other one is the default ViewController.swift

I intend to include all the functionalities of getting and parsing Json data in the loadApi.swift. Bellow is the code

import Foundation

var arr: Array = [String]()

func loadApi(){

    var url = "http://api.wordnik.com:80/v4/word.json/love/definitions?limit=200&includeRelated=true&sourceDictionaries=ahd&useCanonical=true&includeTags=false&api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5"


let session = NSURLSession.sharedSession()

let wordnik = NSURL(string: url)
//println(wordnik)

var task = session.dataTaskWithURL(wordnik!){
    (data, response, error)-> Void in

    if error != nil {
        println("Internet error! Check your Internet Connection")
    } else{
        var error : NSError?
        var vocabData = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &error) as NSArray
        if error != nil{
            println("Parse Json error!")
        }else{
            for items in vocabData{
                let def = items["text"] as String
                arr.append(def)
            }
        }
    }
}
task.resume()
}

well, everything works fine and I can get and parse the Json data from the url and than append them into the "arr" Array. However, when I try to call the "arr" Array in the default ViewController.swift, I got this error saying "missing parameter #2 in call". Bellow is my code in the ViewController.swift

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var textLabel: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()
    loadApi()
    println(arr)
    //error saying "missing parameter #2 in call"


}

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


}

How can I access the "arr" Array that contains all the strings I got from the Json data?

Andrew
  • 45
  • 1
  • 4

1 Answers1

0

Changing the declaration of the array to var arr = [String]() should do the trick.

gasho
  • 1,926
  • 1
  • 16
  • 20
  • Thanks for the swift reply! Well, the error is gone but the print result says that the art is empty! How could that happen? – Andrew Feb 19 '15 at 10:15
  • There must be a completionHandler i suppose. Try using this... [link](http://stackoverflow.com/questions/27081062/swift-how-do-i-return-a-value-within-an-asynchronous-urlsession-function) – gasho Feb 19 '15 at 11:22