PRADIP KUMAR PRADIP KUMAR - 6 months ago 41
Swift Question

Downloading Image from Api and populate Image in CollectionViewController using Swift

I am able to find the response data in array but not able to download and populate in Collection View. I have tried to upload the image from the image container from application but not able to download and upload by API

Code

func get_data_from_url(){


//API calls
let url = NSURL(string: "http://android.eposapi.co.uk/?app_id=A1A2A3A4&app_key=K1K2K3K4&request=gallery")



let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let postString = "gallery"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data,response,error in

if error != nil{
print("error=\(error)")
return
}
//Print out response object
print("response= \(response)")
//print response body
// let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

// print("response data = \(responseString!)")

var json: NSArray!
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as? NSArray
print(json)
print(json[0])

} catch {
print(error)
}

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


}
task.resume()



override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url()


self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)


}



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

// Configure the cell
let image = cell.viewWithTag(1) as! UIImageView

image.image = images[indexPath.row]



return cell
}


Tell me any one solution how to download images of anytype (either png or jpg) and populate in the
UICollectionView
using
mutable urlRequest
/

Answer

Try another way like NSURLSession to download the data

   var url: NSURL = NSURL(string:"http://android.eposapi.co.uk/?app_id=A1A2A3A4&app_key=K1K2K3K4&request=gallery")! 

   var downloadPhotoTask: NSURLSessionDownloadTask =   
  NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: {(location: NSURL, response: NSURLResponse, error: NSError) -> Void in

    var downloadedImage: UIImage = UIImage.imageWithData(NSData.dataWithContentsOfURL(location))
})  
downloadPhotoTask.resume()