1

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
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
minimomo
  • 581
  • 1
  • 6
  • 16
  • The Alamofire Readme explicitly mentions that request are performed *asynchronously*. Have a look at the frequently asked [alamofire] questions: This has been asked and answered repeatedly. – Martin R Jul 18 '16 at 14:56

3 Answers3

2

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.
}
Mtoklitz113
  • 3,828
  • 3
  • 21
  • 40
0

You should call

dispatch_async(dispatch_get_main_queue()) { 
   collectionView.reloadData()
}

when you get a callback from the server.

fiks
  • 1,045
  • 9
  • 21
0

"Networking in Alamofire is done asynchronously."

This means that your request will complete some unknown amount of time after you call searchResults.

Your best strategy is to update your collection view within your success block. (Make sure you make UI updates on the main thread.)

Phillip Mills
  • 30,888
  • 4
  • 42
  • 57