mimi93 mimi93 - 4 months ago 21
Swift Question

array return empty when trying to call from outside the function [swift]

I got this calling api function:

func searchResults(){


let urlString = "http://dev.jocom.com.my/feed"


Alamofire.request(.POST, urlString , parameters: ["req" : "pro_name", "code" : searchString!])

.responseData { response in

switch response.result {
case .Success:

let apiSearchXML = SWXMLHash.parse(response.data!)

for elem in apiSearchXML["rss"]["channel"]["item"]{
self.imageURL.append(elem["thumb_1"].element!.text!)

self.name.append(elem["name"].element!.text!)



}
print(self.name)

case .Failure(let error):
print(error)
}
}

}


It seems ok when i print the output out, the array its containing something. But when i try to call it to display inside my collection view, it didnt return row, and it become empty, why is it?

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

return 1
}


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return self.name.count

}


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! SearchResultsCollectionViewCell

cell.titleLabel.text = "abc"
cell.setNeedsDisplay()
return cell
}

Answer

You need a completion handler for your Async call to complete and then you can fill the array with the results. I believe your name is an array of strings. Do like so:

func searchResults(complete: (names: [String]) -> ()){
let aVar = [String]()
//your code
for elem in apiSearchXML["rss"]["channel"]["item"]{

aVar.append(elem["name"].element!.text!)
}
complete(names: aVar)
//your code
}

Then when you call it, like so:

searchResults { theNames in
 print(theNames)
//Here you have your array of names, use how you want.
}