Swift asynch load image from directory - ios

I have a situation where I am filling out a form and set image from library then storing in a directory.
I am able to get image from the directory but tableview list flickering in the middle of scroll, so I am working with method of dispatch_async but not able to do.
If anybody has a solution, please let me know.
Here is my code.
import UIKit
func getDocumentsURL() -> NSURL {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
return documentsURL
}
func fileInDocumentsDirectory(filename: String) -> String {
let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename)
return fileURL.path!
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var marrEmpData : NSMutableArray!
#IBOutlet var MyTable: UITableView!
#IBAction func addEmpInfo(){
}
override func viewWillAppear(animated: Bool) {
self.getStudentData()
}
func getStudentData()
{
marrEmpData = NSMutableArray()
marrEmpData = ModelManager.getInstance().getAllStudentData()
MyTable.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
MyTable.delegate = self
MyTable.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
//return names.count;
return marrEmpData.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomCell = self.MyTable.dequeueReusableCellWithIdentifier("cells") as! CustomCell
let emp:EmpInfo = marrEmpData.objectAtIndex(indexPath.row) as! EmpInfo
let randomNum = "Image-\(indexPath.row+1).png"
let imagePathOne = fileInDocumentsDirectory(randomNum)
dispatch_async(dispatch_get_main_queue()) {
if let loadedImage = self.loadImageFromPath(imagePathOne) {
print("view Loaded Image: \(loadedImage)")
cell.photo.image = loadedImage
}
else {
cell.photo.image = UIImage(named: "default_user")
}
}
// user profile
cell.name.text = emp.full_name
cell.age.text = emp.age
cell.phone.text = emp.phone
return cell
}
// which one is tapped
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You tapped cell number \(indexPath.row).")
}
// load image of user
func loadImageFromPath(path: String) -> UIImage? {
print("image-----\(path)")
let image = UIImage(contentsOfFile: path)
if image == nil {
print("missing image at: \(path)")
}
print("Loading image from path: \(path)") // this is just for you to see the path in case you want to go to the directory, using Finder.
return image
}
}

You are using dispatch_async but you are dispatching to the main queue which is the thread you are already on. You should dispatch to a background thread, load the image, then dispatch to the main thread and update the UI.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0))
{
let image = self.loadImageFromPath(imagePathOne)
dispatch_async(dispatch_get_main_queue())
{
if let loadedImage = image
{
print("view Loaded Image: \(loadedImage)")
cell.photo.image = loadedImage
}
else
{
cell.photo.image = UIImage(named: "default_user")
}
}
}

Related

Getting black screen on using tab bar while searching using SearchController

I have an app with a tab bar controller embedded in a navigation controller. The app has 2 tabs, the first one(search) has a search bar implemented using the UISearchController. If I switch from this tab to the other tab(downloads) while I'm searching, to the other tab two things happen -
The navigation bar in the second tab(downloads) disappears
When i come back to the first tab(search), it shows a black screen
I have done all this using the storyboard.
this is my SearchViewController
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate{
//MARK: Variables
var papers = [Paper]()
var filteredPapers = [Paper]()
let searchController = UISearchController(searchResultsController: nil)
// MARK: Outlets
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
#IBOutlet var table: UITableView!
#IBOutlet weak var loadingMessageLabel: UILabel!
#IBOutlet weak var retryButton: UIButton!
//MARK: Actions
#IBAction func retryButton(sender: UIButton) {
self.loadingMessageLabel.hidden = false
self.loadingMessageLabel.text = "While the satellite moves into position..."
self.activityIndicator.hidden = false
self.activityIndicator.startAnimating()
self.retryButton.hidden = true
self.getPapersData()
}
// MARK: Table View
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// If in searching mode, then return the number of results else return the total number
// if searchController.active && searchController.searchBar.text != "" {
if searchController.active {
return filteredPapers.count
}
return papers.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let paper: Paper
// if searchController.active && searchController.searchBar.text != "" {
if searchController.active {
paper = filteredPapers[indexPath.row]
} else {
paper = papers[indexPath.row]
}
if let cell = self.table.dequeueReusableCellWithIdentifier("Cell") as? PapersTableCell {
cell.initCell(paper.name, detail: paper.detail)
print(cell)
return cell
}
return PapersTableCell()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let downloadButton = UITableViewRowAction(style: .Normal, title: "Download") { action, index in
var url = String(self.papers[indexPath.row].url)
url = url.stringByReplacingOccurrencesOfString(" ", withString: "%20")
print(url)
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
// Spinner in cell
// var selectCell = self.table.cellForRowAtIndexPath(indexPath) as? PapersTableCell
// selectCell!.downloadSpinner.hidden = false
// Dismiss the download button
self.table.editing = false
Alamofire.download(.GET, url, destination: destination).response { _, _, _, error in
if let error = error {
print("Failed with error: \(error)")
} else {
print("Downloaded file successfully")
}
// selectCell?.downloadSpinner.hidden = true
}
}
downloadButton.backgroundColor = UIColor(red:0.30, green:0.85, blue:0.39, alpha:1.0)
return [downloadButton]
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// the cells you would like the actions to appear needs to be editable
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// you need to implement this method too or you can't swipe to display the actions
}
// MARK: Search
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredPapers = papers.filter { paper in
let categoryMatch = (scope == "All") || (paper.exam == scope)
return categoryMatch && paper.name.lowercaseString.containsString(searchText.lowercaseString)
}
table.reloadData()
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchBar = searchController.searchBar
let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
filterContentForSearchText(searchController.searchBar.text!, scope: scope)
}
func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
}
// MARK: Defaults
override func viewDidLoad() {
super.viewDidLoad()
self.getPapersData()
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
table.tableHeaderView = searchController.searchBar
searchController.searchBar.scopeButtonTitles = ["All", "ST1", "ST2", "PUT", "UT"]
searchController.searchBar.delegate = self
activityIndicator.startAnimating()
}
override func viewWillDisappear(animated: Bool) {
// if searchController.active {
self.searchController.resignFirstResponder()
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: API call
func getPapersData(){
Alamofire.request(.GET, "http://silive.in/bytepad/rest/api/paper/getallpapers?query=")
.responseJSON { response in
self.activityIndicator.stopAnimating()
self.activityIndicator.hidden = true
// If the network works fine
if response.result.isFailure != true {
self.loadingMessageLabel.hidden = true
self.table.hidden = false
//print(response.result) // result of response serialization
let json = JSON(response.result.value!)
for item in json {
// Split the title on the . to remove the extention
let title = item.1["Title"].string!.characters.split(".").map(String.init)[0]
let category = item.1["ExamCategory"].string
let url = item.1["URL"].string
let detail = item.1["PaperCategory"].string
let paper = Paper(name: title, exam: category!, url: url!, detail: detail!)
self.papers.append(paper)
}
self.table.reloadData()
}
// If the network fails
else {
self.retryButton.hidden = false
self.loadingMessageLabel.text = "Check your internet connectivity"
}
}
}
}
And this is my DownloadViewController
import UIKit
import QuickLook
class DownloadViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, QLPreviewControllerDataSource {
var items = [(name:String, url:String)]()
#IBOutlet weak var downloadsTable: UITableView!
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print(items[indexPath.row].url)
// performSegueWithIdentifier("DocumentViewSegue", sender: items[indexPath.row].url)
let previewQL = QLPreviewController() // 4
previewQL.dataSource = self // 5
previewQL.currentPreviewItemIndex = indexPath.row // 6
showViewController(previewQL, sender: nil) // 7
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = self.downloadsTable.dequeueReusableCellWithIdentifier("Download Cell") as? DownloadsTableCell {
cell.initCell(items[indexPath.row].name, detail: "", fileURL: items[indexPath.row].url)
return cell
}
return DownloadsTableCell()
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
// let fileManager = NSFileManager.defaultManager()
//
// // Delete 'hello.swift' file
//
// do {
// try fileManager.removeItemAtPath(String(items[indexPath.row].url))
// }
// catch let error as NSError {
// print("Ooops! Something went wrong: \(error)")
// }
items.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
override func viewDidAppear(animated: Bool) {
items.removeAll()
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
// now lets get the directory contents (including folders)
do {
let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
// print(directoryContents)
for var file in directoryContents {
print(file.lastPathComponent)
print(file.absoluteURL)
// Save the data in the list as a tuple
self.items.append((file.lastPathComponent!, file.absoluteString))
}
} catch let error as NSError {
print(error.localizedDescription)
}
downloadsTable.reloadData()
}
// MARK: Preview
func numberOfPreviewItemsInPreviewController(controller: QLPreviewController) -> Int {
return items.count
}
func previewController(controller: QLPreviewController, previewItemAtIndex index: Int) -> QLPreviewItem {
return NSURL(string: items[index].url)!
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
//do something
super.viewWillAppear(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Looks like the view that your UISearchController is attached to gets removed from the view hierarchy. You can think of the UISearchController as being presented modally when you start searching, and the definesPresentationContext property indicates which UIViewController would be the one to present it (more on this).
One of the ways to fix this would be reconfiguring your storyboard so that each tab has its own UINavigationController (in case you need it for both):
Instead of (what I suspect you have now):
And if you want to dismiss UISearchController when the tab switches, add this override to the ViewController:
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
searchController.active = false
}

TableViewController does not appear for a few seconds after Transition

I have a tabbarcontroller with four tableviewcontrollers that are connected by navigation controllers. The tableviews are popualted by images and text download from the internet by a XMLParser. When the app loads, after the splash screen, the screen goes black for a few seconds, then the first table view appears. Tab clicks on the other tableviews also lag. How can I display something in place of a black screen or unresponsive interface while the tableview controller's data is downlaoded?
The code of one of the tableviews:
import UIKit
class TopicsTableViewController: UITableViewController, XMLParserDelegate {
var xmlParser : XMLParser!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://sharontalon.com/feed")
xmlParser = XMLParser()
xmlParser.delegate = self
xmlParser.startParsingWithContentsOfURL(url!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: XMLParserDelegate method implementation
func parsingWasFinished() {
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return xmlParser.arrParsedData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("idCell", forIndexPath: indexPath)
let currentDictionary = xmlParser.arrParsedData[indexPath.row] as Dictionary<String, String>
let url = currentDictionary["enclosure"]
let data = NSData(contentsOfURL: url!.asNSURL) //make sure your image in this url does exist, otherwise unwrap in a if let check
let description = currentDictionary["description"]
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.textLabel?.text = currentDictionary["title"]
cell.detailTextLabel?.text = String(htmlEncodedString: description!)
cell.detailTextLabel?.numberOfLines = 3;
cell.textLabel?.numberOfLines = 2;
cell.imageView?.image = UIImage(data: data!)
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let dictionary = xmlParser.arrParsedData[indexPath.row] as Dictionary<String, String>
let tutorialLink = dictionary["link"]
let publishDate = dictionary["pubDate"]
let tutorialViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("idTutorialViewController") as! TutorialViewController
tutorialViewController.tutorialURL = NSURL(string: tutorialLink!)
tutorialViewController.publishDate = publishDate
showDetailViewController(tutorialViewController, sender: self)
}
This may be caused by a simple threading issue, give this a shot and if it doesn't work I'll try to help you further:
First move your resource heavy operation to a background thread:
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://sharontalon.com/feed")
xmlParser = XMLParser()
xmlParser.delegate = self
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
self.xmlParser.startParsingWithContentsOfURL(url!)
})
}
Next, move any code that will update the user interface to the foreground thread:
func parsingWasFinished() {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
If this doesn't resolve your issue, let me know any I'll remove this answer and rethink your problem.
Reloading table data has to be on the main thread of the table to be renewed immediately.
func parsingWasFinished() {
self.tableView.reloadData()
}
Would be:
func parsingWasFinished() {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}

I am trying to fetch image from a URL and make it as a thumbnail for my contacts in my application

I can fetch the image from a url and able to display the image in a UIImageView in my DetailViewController. I would like to display the same image from this URL as a thumbnail in my tableviewcell.
My viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
self.UrlField.text = contact.Imageurl
let urlString = UrlField.text
loadImageView(urlString)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
let urlString = UrlField.text
loadImageView(urlString)
textField.resignFirstResponder()
return true
}
In this function I try to fetch the image from the URL
func loadImageView(url : String){
self.contact.Imageurl = url
self.contact.data = nil
let DatatoImage: (NSData?) -> Void = {
if let d = $0 {
let image = UIImage(data: d)
self.imageView.image = image
}else{
self.imageView.image = nil
}
}
if let d = contact.data {
DatatoImage(d)
} else {
contact.loadImage(DatatoImage)
}
}
In my cellForRowAtIndexPath I managed to load an image that I have hardcoded in my folder and named it as "images1.jpeg"
cell.imageView?.image = UIImage (named: "images1.jpeg", inBundle: nil, compatibleWithTraitCollection: nil)
MainViewController
import UIKit
class MasterTableViewController: UITableViewController, ContactDetailTableViewControllerDelegate {
var contacts: [ContactListEntry] = []
var currentContact: ContactListEntry!
var detailObject: ContactDetailTableViewController!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
#IBAction func addContact(sender: UIBarButtonItem) {
currentContact = ContactListEntry(firstName: "", lastName: "", address: "", Imageurl: "")
contacts.append(currentContact)
performSegueWithIdentifier("showDetail", sender: self)
}
/* override func viewWillAppear(animated: Bool) {
if self.currentContact == nil || self.currentContact.isEmpty()
{
if count(contacts) > 0
{
contacts.removeLast()
}
}
tableView.reloadData()
}*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
/*override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}*/
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return contacts.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("contactcell", forIndexPath: indexPath) as! UITableViewCell
let contact = contacts[indexPath.row]
cell.textLabel?.text = "\(contact.firstName) \(contact.lastName)"
cell.imageView?.image = UIImage (named: "images1.jpeg", inBundle: nil, compatibleWithTraitCollection: nil)
let url = NSURL(string: "<# place your URL here #>")
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let cell = sender as? UITableViewCell
{
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
if (segue.identifier == "showDetail")
{
if let dvc = segue.destinationViewController as? ContactDetailTableViewController{
let indexPath = tableView.indexPathForCell(cell)!
currentContact = contacts[indexPath.row]
dvc.contact = currentContact
}}}
if let dvc = segue.destinationViewController as? ContactDetailTableViewController
{
dvc.contact = currentContact
dvc.delegate = self
}
}
func masterViewController(dvc: ContactDetailTableViewController, didUpdate contact: Person)
{
dvc.contact = currentContact
dvc.delegate = self
dvc.dismissViewControllerAnimated(true, completion: nil)
navigationController?.popToViewController(self, animated: true)
tableView.reloadData()
}
override func viewDidAppear(animated: Bool) {
tableView.reloadData()
}
}
/* Create our configuration first In view did load */
let configuration =
NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForRequest = 15.0
configuration.URLCache=NSURLCache(memoryCapacity: 4*1024*1024, diskCapacity: 20*1024*1024, diskPath: "CustomName"))
configuration.requestCachePolicy=NSURLRequestUseProtocolCachePolicy;
/* Now create our session which will allow us to create the tasks */
var session: NSURLSession!
session = NSURLSession(configuration: configuration,
delegate: self,
delegateQueue: nil)
/* Now attempt to download the contents of the URL in tableView cellForRowAtIndexpath */
let url = NSURL(string: "<# place your URL here #>")
task=session.dataTaskWithRequest(url!, completionHandler: { (NSData!, NSURLResponse!, NSError!) -> Void in
cell.imageView.image=UIImage(data: NSData))
})
task.start()
You can also set the cache,so that next tym when the request is fired then it is called from cache

Obtaining image details in detailviewcontroller when clicking image in collectionviewcontroller

My CollectionViewController contains an image. When I click the image in my CollectionViewController it takes me to the detailviewcontroller where I want to edit the details of the image. When I enter the details such as an URL, then click the back button, it should fetch the image from the URL and replace the image in my CollectionViewController.
I have two problems:
When I click the image in my CollectionViewController it opens the detailviewcontroller, but it doesn't show the url of the image I clicked.
When I click the back button it does not take me back to the CollectionViewController.
import Foundation
class Photo {
var url: String = ""
var data: NSData? = nil
var Title: String = ""
var Tags: String = ""
func loadImage(completionHandler: (data: NSData?) ->Void) {
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
dispatch_async(queue) {
let mainQueue = dispatch_get_main_queue()
if let url = NSURL(string: self.url) {
if let data = NSData(contentsOfURL: url) {
sleep(3)
dispatch_async(mainQueue) {
self.data = data
completionHandler(data: data)
}
return
}
dispatch_async(mainQueue) {
completionHandler(data: nil)
}
}
}
}
}
detailviewcontroller
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var photo: Photo!
#IBOutlet weak var textURL: UITextField!
#IBOutlet weak var textTitle: UITextField!
#IBOutlet weak var textTags: UITextField!
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
let urlString = textField.text
photo.url = urlString
let DatatoImage: (NSData?) -> Void = {
if let d = $0 {
let image = UIImage(data: d)
self.imageView.image = image
} else {
self.imageView.image = nil
}
//textField.resignFirstResponder()
}
if let d = photo.data {
DatatoImage(d)
textField.resignFirstResponder()
let image = UIImage(data: d)
self.imageView.image = image
} else {
photo.loadImage(DatatoImage)
}
return true
}
}
My masterViewController
import UIKit
let reuseIdentifier = "Cell"
class PhotosCollectionViewController: UICollectionViewController {
var photos = Array<Photo>()
override func viewDidLoad() {
super.viewDidLoad()
let photo = Photo()
photo.url = "http://www.griffith.edu.au/__data/assets/image/0019/632332/gu-header-logo.png"
photos.append(photo)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.registerClass(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//#warning Incomplete method implementation -- Return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as PhotoCollectionViewCell
let photo = photos[indexPath.row]
if let d = photo.data {
let image = UIImage(data: d)
cell.imageView.image = image
photo.url = "\(photo.url)"
photo.Title = "\(photo.Title)"
} else {
photo.loadImage {
if $0 != nil {
collectionView.reloadItemsAtIndexPaths([indexPath])
}
}
}
return cell
}
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let indexPath = sender as? NSIndexPath {
let photo = photos[indexPath.row]
}
if (segue.identifier == "showDetail") {
if let dvc = segue.destinationViewController as? ViewController {
let photo = Photo()
dvc.photo = photo
}
}
}
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
performSegueWithIdentifier("showDetail", sender: indexPath)
return true
}
In your prepareForSegue method, you have this line,
let photo = Photo()
This creates a new Photo object, it doesn't get the one you were displaying in the cell you selected. You got a reference to the correct one in your if let statement. Use that one (let photo = photos[indexPath.row]).
As for the back button, you shouldn't have to write any code to make that work, if that back button is the one you get automatically when you push to a new controller.

Swift Displaying Parse Image in TableView Cell

I am attempting to display the users image that is saved to parse property "image". I have been able to display my username with no issue, but I can't seem to be able to get my image to appear. Should I be casting this information as UIImage? Am I correctly calling where the file is stored?
Here is my code:
import UIKit
class SearchUsersRegistrationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var userArray : NSMutableArray = []
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
loadParseData()
var user = PFUser.currentUser()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadParseData() {
var query : PFQuery = PFUser.query()
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]!, error:NSError!) -> Void in
if error == nil {
if let objects = objects {
println("\(objects.count) users are listed")
for object in objects {
self.userArray.addObject(object)
}
self.tableView.reloadData()
}
} else {
println("There is an error")
}
}
}
let textCellIdentifier = "Cell"
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.userArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! SearchUsersRegistrationTableViewCell
let row = indexPath.row
var individualUser = userArray[row] as! PFUser
var username = individualUser.username as String
var profilePicture = individualUser["image"] as? UIImage
cell.userImage.image = profilePicture
cell.usernameLabel.text = username
return cell
}
#IBAction func finishAddingUsers(sender: AnyObject) {
self.performSegueWithIdentifier("finishAddingUsers", sender: self)
}
}
The photos are saved in a PFFile and not as a UIImage..
What makes your code the following:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! SearchUsersRegistrationTableViewCell
let row = indexPath.row
var individualUser = userArray[row] as! PFUser
var username = individualUser.username as String
var pfimage = individualUser["image"] as! PFFile
pfimage.getDataInBackgroundWithBlock({
(result, error) in
cell.userImage.image = UIImage(data: result)
})
cell.usernameLabel.text = username
return cell
}
See more in the docs
fileprivate func getImage(withCell cell: UITableViewCell, withURL url: String) {
Alamofire.request(url).responseImage { (image) in
/* Assign parsed Image */
if let parsedImage = image.data {
DispatchQueue.main.async {
/* Assign Image */
cell.imageView?.image = UIImage(data: parsedImage)
/* Update Cell Content */
cell.setNeedsLayout()
cell.layoutIfNeeded()
}
}
}
}

Resources