I am uploading a single file in a table view cell using AFNetworking.
Uploading is working alright. But when I scroll my cell off view, the progress is gone or some times it displays different progress values like 20% or 50%, and again 30%.
This is my code:
//Tableview Cell configure
var cell : ChattingPhotoCell!
if message.vendorType == .Receiver {
//Receive Image message
cell = tableView.dequeueReusableCell(withIdentifier: "ReceiveChattingPhotoCell") as! ChattingPhotoCell
if cell == nil {
cell = Bundle.main.loadNibNamed("ReceiveChattingPhotoCell", owner: self, options: nil)?[0] as! ChattingPhotoCell
}
cell.reloadDelegate = self
cell.mDelegate = self
cell.accessoryType = cell.isSelected ? .checkmark : .none
cell.conficureImageCell(msg: message,indexPath: indexPath)
} else {
// Send Image Message
cell = tableView.dequeueReusableCell(withIdentifier: "SenderChattingPhotoCell") as! ChattingPhotoCell
if cell == nil {
cell = Bundle.main.loadNibNamed("SenderChattingPhotoCell", owner: self, options: nil)?[0] as! ChattingPhotoCell
}
cell.reloadDelegate = self
cell.mDelegate = self
cell.accessoryType = cell.isSelected ? .checkmark : .none
cell.conficureImageCell(msg: message,indexPath: indexPath)
}
//MyCell code
func conficureImageCell(msg:Message,indexPath:IndexPath) {
self.message = msg
self.indexPath = indexPath
if self.message.vendorType == .Sender {
self.senderCellConfigure()
} else {
self.receiverCellConfigure()
}
}
// sender configure methods
func senderCellConfigure() {
// Send Message
if message.upload == 1 {
self.btnRetry.isHidden = true
}else{
self.btnRetry.isHidden = false
}
if message.is_send == 0 && !self.message.isUploadMedia && message.upload != 1 {
let image = UIImage.init(contentsOfFile: documentDir.path)
if image != nil {
self.uploadImageToServer(ArrImage_Video: NSMutableArray.init(array: [image!]), strMsgType: "3")
}
}
if self.message.isUploadMedia {
self.progressView.isHidden = false
self.btnRetry.isHidden = true
} else {
self.progressView.isHidden = true
}
}
// MARK:- WebserviceCalling // Hiren
func uploadImageToServer(ArrImage_Video:NSMutableArray,strMsgType: String){
self.message.isUploadMedia = true
self.btnRetry.isHidden = true
if self.str_media_url.isBlank {
self.progressView.isHidden = false
let accessToken = Singleton.sharedSingleton.retriveFromUserDefaults(key:Global.kLoggedInUserKey.AccessToken)
print(accessToken!)
let param: NSMutableDictionary = NSMutableDictionary()
param.setValue(fromJID, forKey: "from_user_id")
param.setValue(toJID, forKey: "to_user_id")
param.setValue(strMsgType, forKey: "message_type")
param.setValue("ABC", forKey: "from_user_name")
param.setValue(UIDevice.current.model, forKey: "device_type")
param.setValue("897584acac541d73d5f01f294fe944ddb35b6f67ea894e9ac29b03c7da69ca48", forKey: "device_token")
param.setValue("jpeg", forKey: "file_type")
param.setValue("135", forKey: "message_id")
param.setValue(accessToken, forKey: "access_token")
AFAPIMaster.sharedAPIMaster.PostMediatoServer_chat(params: param, arrMedia: ArrImage_Video, showLoader: false, enableInteraction: true, viewObj: self, onSuccess: {
(DictResponse) in
let dictResponse: NSDictionary = DictResponse as! NSDictionary
let dictData: NSDictionary = dictResponse.object(forKey: "SuccessResponse") as! NSDictionary
let media_url = dictData.object(forKey: "media_url") as? String ?? ""
let media_id = dictData.object(forKey: "id") as? Int ?? 0
let thumb_image = dictData.object(forKey: "thumb_image") as? String ?? ""
print(media_url)
print(thumb_image)
DispatchQueue.main.async {
self.progressView.isHidden = true
let onChatMaster = OnChatMasterTable()
let messageObj = onChatMaster.getMessageFromDB(strMessageID: self.msgID, strFromUId: self.fromJID, strToUId: self.toJID)
messageObj.media_url = media_url
messageObj.thumb_url = thumb_image
messageObj.upload = 1
messageObj.message = self.imageName
messageObj.media_id = media_id
self.str_media_ID = String(media_id)
self.message.media_id = media_id
DBHelper.sharedInstance.queue?.inDatabase() {
db in
DBHelper.sharedInstance.chilaxDB.open()
let strUpdQuery = "UPDATE OnChat_Master SET upload = 1 , media_url = '\(media_url)', thumb_url = '\(thumb_image)' , media_id = \(media_id) where message_id = '\(messageObj.message_id)' AND from_user_id = '\(messageObj.from_user_id)' AND to_user_id = '\(messageObj.to_user_id)'"
DBHelper.sharedInstance.chilaxDB.executeUpdate(strUpdQuery, withArgumentsIn: [])
DBHelper.sharedInstance.chilaxDB.close()
}
//onChatMaster.updateMessageInDB(messsageObj: messageObj)
self.sendMediaDataToSender(media_url: media_url, thumb_image: thumb_image,strMediaId:self.str_media_ID)
self.message.isUploadMedia = false
}
}, displayProgress: {
(progress) in
DispatchQueue.main.async {
let progressTask : Float = Float((progress as! Progress).fractionCompleted)
print(progressTask)
self.progressView.setProgress(progressTask, animated: true)
}
}, onFailure: {
self.progressView.setProgress(0.0, animated: true)
self.progressView.isHidden = true
self.btnRetry.isHidden = false
self.message.isUploadMedia = false
})
} else {
self.sendMediaDataToSender(media_url: str_media_url, thumb_image: str_thumb_url, strMediaId: str_media_ID)
}
}
I reuse cell using table view deque methods. Any wrong in this code.
Related
I have a JSON response from Alamofire. I want populate my tableviews rolls with the JSON but only one roll is displayed. other JSONs are not loaded into to custom tableView cells
If segmentedControl.selectedSegmentIndex == 0 {
cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row - 1]
cell.currentRideDriverPassengerName.text = currentDriverRidePassaengerDataModel.name
cell.currentRideDriverPassengerLocation.text = currentDriverRidePassaengerDataModel.location
cell.currentRideDriverPassengerDestination.text = currentDriverRidePassaengerDataModel.destination
cell.currentRideDriverPassengerPrice.text = String(currentDriverRidePassaengerDataModel.price)
cell.currentRideDriverPassengerSeat.text = String(currentDriverRidePassaengerDataModel.seat)
cell.currentRideDriverPassengerDistance.text = String(currentDriverRidePassaengerDataModel.distance)
cell.currentRideDriverPassengerImage.sd_setImage(with: URL(string: currentDriverRidePassaengerDataModel.image))
}else if segmentedControl.selectedSegmentIndex == 1 {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row - 1]
}
return cell
}
}
func getCurrentRideData(url: String) {
Alamofire.request(url, method: .get).responseJSON {
response in
if response.result.isSuccess {
print("Sucess Got the Current Ride Data")
let currentRideJSON : JSON = JSON(response.result.value!)
let currentDriverPassenger : JSON = JSON(response.result.value!)
print(currentRideJSON)
print("This is passager\(currentDriverPassenger)")
self.updateCurrentRideData(json: currentRideJSON)
self.uodateCurrentRideDriverPassangerData(json: currentDriverPassenger)
}else {
print("error)")
}
}
}
func uodateCurrentRideDriverPassangerData(json : JSON) {
currentDriverRidePassaengerDataModel.image = json["ride"][0] ["riders"][0]["image"].stringValue
currentDriverRidePassaengerDataModel.name = json["ride"][0]["riders"][0]["name"].stringValue
currentDriverRidePassaengerDataModel.location = json["ride"][0]["riders"][0]["startLocation"].stringValue
currentDriverRidePassaengerDataModel.destination = json["ride"][0]["riders"][0]["stopLocation"].stringValue
currentDriverRidePassaengerDataModel.price = json["ride"][0]["rider"][0]["price"].intValue
currentDriverRidePassaengerDataModel.seat = json["ride"][0]["riders"][0]["seatNumber"].intValue
currentDriverRidePassaengerDataModel.distance = json["ride"][0]["riders"][0]["distance"].intValue
}
I want my JSON to populate my table rolls not just one roll
Try This
func uodateCurrentRideDriverPassangerData(json : JSON)
{
for i in 0...json.count-1
{
currentDriverRidePassaengerDataModel.image = json["ride"][i] ["riders"][i]["image"].stringValue
currentDriverRidePassaengerDataModel.name = json["ride"][i]["riders"][i]["name"].stringValue
currentDriverRidePassaengerDataModel.location = json["ride"][i]["riders"][i]["startLocation"].stringValue
currentDriverRidePassaengerDataModel.destination = json["ride"][i]["riders"][i]["stopLocation"].stringValue
currentDriverRidePassaengerDataModel.price = json["ride"][i]["rider"][i]["price"].intValue
currentDriverRidePassaengerDataModel.seat = json["ride"][i]["riders"][i]["seatNumber"].intValue
currentDriverRidePassaengerDataModel.distance = json["ride"][i]["riders"][i]["distance"].intValue
}
}
I have coded a UIViewController that handles the upload (Only) for files to iCloud. So far it works well but I was trying to make it better with Network Changes using Reachability.
The way I handle the changes is:
lazy var searchQuery:NSMetadataQuery = {
let searchQueryTemp = NSMetadataQuery()
searchQueryTemp.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
let searchPredicate = NSPredicate.init(format: "%K BEGINSWITH %# && NOT %K.pathExtension = ''", argumentArray: [NSMetadataItemPathKey,trackFileManager.appICloudExportedMusic!.path,NSMetadataItemFSNameKey])
searchQueryTemp.predicate = searchPredicate
return searchQueryTemp
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("\(logClassName): viewWillAppear")
appDelegate.appReachabilityDelegate = self
NotificationCenter.default.addObserver(self, selector: #selector(updateDataWithNotification), name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: searchQuery)
NotificationCenter.default.addObserver(self, selector: #selector(updateDataWithNotification), name: NSNotification.Name.NSMetadataQueryDidUpdate, object: searchQuery)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
updateSearch()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("\(logClassName): viewWillDisappear")
NotificationCenter.default.removeObserver(self)
}
#objc func updateDataWithNotification(notification: NSNotification){
print("\(logClassName): updateDataWithNotification \(searchQuery.results.count)")
if let queryObject = notification.object as? NSMetadataQuery{
if searchQuery == queryObject{
print("\(logClassName): Query count = \(queryObject.results.count)")
var iCloudAlbumArrayTemp = [FileIcloudAlbumHeader]()
/* Get the query results [URL] only files */
for result in queryObject.results{
/* Get Metadata for file */
if let metadataItem = result as? NSMetadataItem{
if let urlItem:URL = metadataItem.value(forKey: NSMetadataUbiquitousItemURLInLocalContainerKey) as? URL{
if var urlItemPath = urlItem.path.components(separatedBy: "Exported Music").last{
urlItemPath = String(urlItemPath.dropFirst())
let urlItemArray = urlItemPath.components(separatedBy: "/")
if urlItemArray.count == 3{
var albumICloudTrack = AlbumICloudTrack(url: urlItem)
let isUpdated:Bool = metadataItem.value(forKey: NSMetadataUbiquitousItemIsUploadedKey) as! Bool
let isUpdating: Bool = metadataItem.value(forKey: NSMetadataUbiquitousItemIsUploadingKey) as! Bool
let isDownloading:Bool = metadataItem.value(forKey: NSMetadataUbiquitousItemIsDownloadingKey) as! Bool
if isUpdated{
albumICloudTrack.status = .available
}
else{
if isUpdating{
let perInt = Int(metadataItem.value(forKey: NSMetadataUbiquitousItemPercentUploadedKey) as! Double)
print("\(logClassName): isUpdating: PerInt = \(perInt)")
let perDouble = metadataItem.value(forKey: NSMetadataUbiquitousItemPercentUploadedKey) as! Double
print("\(logClassName): isUpdating: PerInt = \(perDouble)")
albumICloudTrack.percentatge = Int(metadataItem.value(forKey: NSMetadataUbiquitousItemPercentUploadedKey) as! Double)
albumICloudTrack.status = .updating
}
else if isDownloading{
albumICloudTrack.status = .downloading
}
else{
albumICloudTrack.status = .notAvailable
}
}
/* Find Album */
var tempUrl = urlItem.deletingLastPathComponent()
let albumName = tempUrl.lastPathComponent
tempUrl = tempUrl.deletingLastPathComponent()
let artistName = tempUrl.lastPathComponent
//print("\(logClassName): Artist Name = \(artistName) && Album Name = \(albumName)")
let albumHeaderInex = findAlbumHeader(withArtistName: artistName, andAlbum: albumName, in: iCloudAlbumArrayTemp)
if albumHeaderInex != -1{
//print("\(logClassName): Appending Already exists")
iCloudAlbumArrayTemp[albumHeaderInex].urlTrackArray.append(albumICloudTrack)
}
else{
//print("\(logClassName): Creating New Header Album")
var albumHeader = FileIcloudAlbumHeader(artistName: artistName, albumName: albumName, url: urlItem.deletingLastPathComponent())
albumHeader.urlTrackArray.append(albumICloudTrack)
iCloudAlbumArrayTemp.append(albumHeader)
}
}
else{
print("\(logClassName): Discarting Item = \(urlItemPath)")
}
}
}
}
}
/* Copy content for updating Expanded status */
for iCloudAlbumIndex in iCloudAlbumArray.indices{
for iCloudAlbumTempIndex in iCloudAlbumArrayTemp.indices{
if iCloudAlbumArray[iCloudAlbumIndex].artistName == iCloudAlbumArrayTemp[iCloudAlbumTempIndex].artistName && iCloudAlbumArray[iCloudAlbumIndex].albumName == iCloudAlbumArrayTemp[iCloudAlbumTempIndex].albumName{
iCloudAlbumArrayTemp[iCloudAlbumTempIndex].isSelected = iCloudAlbumArray[iCloudAlbumIndex].isSelected
}
}
}
iCloudAlbumArray.removeAll()
for iCloudAlbumTempIndex in iCloudAlbumArrayTemp.indices{
iCloudAlbumArray.append(iCloudAlbumArrayTemp[iCloudAlbumTempIndex])
iCloudAlbumArray[iCloudAlbumTempIndex].urlTrackArray.sort {
return $0.trackName < $1.trackName
}
}
/* Reload table */
iCloudExportsTableView.reloadData()
}
}
}
The main problem here is that I see the file is updating in "Files" but
let isUpdating: Bool = metadataItem.value(forKey: NSMetadataUbiquitousItemIsUploadingKey) as! Bool
returns false
What am I not taking in consideration?
Thank you in advance
I have realised that despite NSMetadataUbiquitousItemIsUploadingKey returns false, NSMetadataUbiquitousItemPercentUploadedKey stills returns a number so:
let perDouble = metadataItem.value(forKey: NSMetadataUbiquitousItemPercentUploadedKey) as? Double ?? 100.00
if isUpdated{
albumICloudTrack.status = .available
}
else{
if isUpdating || perDouble < 100.00{
print("\(logClassName): isUpdating: perDouble = \(perDouble)")
albumICloudTrack.percentatge = Int(metadataItem.value(forKey: NSMetadataUbiquitousItemPercentUploadedKey) as! Double)
albumICloudTrack.status = .updating
}
Any other thoughts?
here i had divided into sections in it each section there are rows depending on count so for every row the radio button will be there and i need to make active only one radio button for all of the sections but i am unable to implement it and the image for sections will be shown here and my code is
#IBAction func paymentRadioAction(_ sender: KGRadioButton) {
let chekIndex = self.checkIsPaymentRadioSelect.index(of: sender.tag)
if sender.isSelected {
} else{
if(chekIndex == nil){
self.checkIsPaymentRadioSelect.removeAll(keepingCapacity: false)
self.checkIsPaymentRadioSelect.append(sender.tag)
self.shippingTableView.reloadData()
}
}
}
here is the code for cell for row at indexpath
let cell = tableView.dequeueReusableCell(withIdentifier: "shippingCell", for: indexPath) as! shippingMethodTableViewCell
var key = self.keys[indexPath.section]
print(key)
var a :[Any] = arrayss[key] as! [Any]
var dictionary = a[indexPath.row] as! [String:Any]
let name = dictionary["name"]
let price = dictionary ["price"]
cell.methodNameLabel.text = name as! String
cell.priceLabel.text = price as! String
let checkIndex = self.checkIsPaymentRadioSelect.index(of: indexPath.row)
if(checkIndex != nil){
cell.radioButton.isSelected = true
}else{
cell.radioButton.isSelected = false
}
return cell
}
Here you don't have to use an array to keep track of the selected radio button
Make chekIndex as global variable of type IndexPath as var chekIndex:IndexPath?
and modify the code as below
#IBAction func paymentRadioAction(_ sender: KGRadioButton) {
let center = sender.center;
let centralPOint = sender.superview?.convert(sender.center, to:self.shippingTableView )
let indexPath = self.shippingTableView.indexPathForRow(at: centralPoint)
if sender.isSelected {
} else{
chekIndex = indexPath
self.shippingTableView.reloadData()
}
}
let cell = tableView.dequeueReusableCell(withIdentifier: "shippingCell", for: indexPath) as! shippingMethodTableViewCell
var key = self.keys[indexPath.section]
print(key)
var a :[Any] = arrayss[key] as! [Any]
var dictionary = a[indexPath.row] as! [String:Any]
let name = dictionary["name"]
let price = dictionary ["price"]
cell.methodNameLabel.text = name as! String
cell.priceLabel.text = price as! String
if checkIndex == indexPath {
cell.radioButton.isSelected = true
} else {
cell.radioButton.isSelected = false
}
return cell
}
here i had implemented a custom design like the image shown here i need to active the radio button depending on my web services data. In web services one key value pair i was receiving 0 & 1 only in that if it is 1 then i need to make active the radio button any help how to implement ?
here is the code for my radio button
#IBAction func selectRadioButton(_ sender: KGRadioButton) {
let chekIndex = self.checkIsRadioSelect.index(of: sender.tag)
let checkIndex = self.checkIsButtonEnable.index(of: sender.tag)
if sender.isSelected {
} else{
if(chekIndex == nil){
self.checkIsRadioSelect.removeAll(keepingCapacity: false)
self.checkIsRadioSelect.append(sender.tag)
self.checkIsButtonEnable.removeAll(keepingCapacity: false)
self.checkIsButtonEnable.append(sender.tag)
self.tableDetails.reloadData()
}
}
}
here is the code for table view
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! addressTableViewCell
tableDetails.isHidden = false
myActivityIndicator.stopAnimating()
let arr = detailsArray[indexPath.row]
cell.nameLabel.text = arr["name"]as? String
cell.addressLabel.text = arr["address"]as? String
let mobilenumber : Int = arr["number"] as! Int
cell.mobileNumberLabel.text = String(describing: mobilenumber)
let defaultaddress : Int = arr["default"] as! Int
cell.radioButton.tag = indexPath.row
cell.editButton.tag = indexPath.row
cell.deleteButton.tag = indexPath.row
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
if(checkIndex != nil){
cell.radioButton.isSelected = true
cell.editButton.isHidden = false
cell.deleteButton.isHidden = false
}else{
cell.radioButton.isSelected = false
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
}
return cell
In your cellForRowAtIndexPath method update code like below
My suggestion is Don't set indexPath.row as tag while reusing tableView cells it won't give you better result.Make some unique id as tag. or do some math calculation something adding/multiplying with numbers.
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! addressTableViewCell
tableDetails.isHidden = false
myActivityIndicator.stopAnimating()
let arr = detailsArray[indexPath.row]
cell.nameLabel.text = arr["name"]as? String
cell.addressLabel.text = arr["address"]as? String
let mobilenumber : Int = arr["number"] as! Int
cell.mobileNumberLabel.text = String(describing: mobilenumber)
cell.radioButton.tag = indexPath.row
cell.editButton.tag = indexPath.row
cell.deleteButton.tag = indexPath.row
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
cell.radioButton.isSelected = false
if let isDefault = arr["default"] as? Bool { // i think it won't be Integer it will be Bool,please debug & check it
cell.radioButton.isSelected = isDefault
cell.editButton.isHidden = false
cell.deleteButton.isHidden = false
}
let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
if(checkIndex != nil){
cell.radioButton.isSelected = true
cell.editButton.isHidden = false
cell.deleteButton.isHidden = false
}
Change the below line of code.
let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row) //delete this line
let checkIndex = arr["default"] as! Int //use radio button key.
#IBAction func selectRadioButton(_ sender: KGRadioButton) {
let arr = detailsArray[sender.tag]
if sender.isSelected {
arr["default"] = #"0"
} else{
arr["default"] = #"1"
}
self.tableDetails.reloadData()
}
I'm getting JSON data from an API and parsing that data in objects, which are then simply stored in an array of objects. The objects themselves contain data about articles from a newspaper. However, I need to filter that data. Some of the objects I'm getting from my JSON actually have no article content because they are pictures and not articles (i.e. some of the "nodes" from the API's JSON have content that I don't want to see in my table view).
In my JSON-parsing function, I've tried to make it so that the parsed object will only get added to the array of parsed objects if the character count of the "articleContent" variable is above 40. Here is what it looked like.
if issueElement.articleContent.characters.count > 40 {
self.currentIssueObjects.addObject(issueElement)
}
However, this simply does not work. I get the typical "unexpectedly found nil while unwrapping an Optional value" error message (I don't get a specific line for the error). How can I make this work ? I'm essentially trying to prevent the array from having objects with empty articleContent, because then that screws up my table view (empty cells, duplicates, etc...).
Here is my cellForRowAtIndexPath code, and my JSON-parsing code:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
let row = indexPath.row
guard let cell = tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as? CurrentIssueArticlesTableViewCell else {
print ("error: currentIssueTableView cell is not of class CurrentIssueArticlesTableViewCell, we will use EditorialsTableViewCell instead")
return tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as! EditorialsTableViewCell
}
let currentIssueObject = currentIssueObjects.objectAtIndex(indexPath.row) as! IssueElement
let title = currentIssueObject.title ?? ""
let timeStampDateObject = NSDate(timeIntervalSince1970: NSTimeInterval(currentIssueObject.timeStamp))
let timeStampDateString = dateFormatter.stringFromDate(timeStampDateObject) ?? "Date unknown"
if let author = currentIssueObject.author {
cell.currentIssueArticlesAuthorLabel!.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
cell.currentIssueArticlesAuthorLabel!.text = author
}
let issueNumber = currentIssueObject.issueNumber ?? ""
let volumeNumber = currentIssueObject.volumeNumber ?? ""
let articleContent = currentIssueObject.articleContent ?? ""
let nodeID = currentIssueObject.nodeID ?? 0
cell.currentIssueArticlesHeadlineLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
cell.currentIssueArticlesHeadlineLabel.text = title
cell.currentIssueArticlesPublishDateLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
cell.currentIssueArticlesPublishDateLabel.text = timeStampDateString
if row == 0 {
cell.userInteractionEnabled = false
let imageURL = (currentIssueObjects.objectAtIndex(row) as! IssueElement).imageURL
cell.currentIssueArticlesHeadlineLabel.textColor = UIColor.clearColor()
cell.currentIssueArticlesAuthorLabel.textColor = UIColor.clearColor()
cell.currentIssueArticlesPublishDateLabel.textColor = UIColor.clearColor()
cell.request?.cancel()
if let image = self.imageCache.objectForKey(imageURL!) as? UIImage {
cell.currentIssueArticlesBackgroundImageView.image = image
} else {
cell.currentIssueArticlesBackgroundImageView.image = UIImage(named: "reveal Image")
cell.request = Alamofire.request(.GET, imageURL!).responseImage() { response in
if response.result.error == nil && response.result.value != nil {
self.imageCache.setObject(response.result.value!, forKey: response.request!.URLString)
cell.currentIssueArticlesBackgroundImageView.image = response.result.value
} else {
}
}
}
cell.currentIssueArticlesBackgroundImageView.hidden = false
}
else {
cell.currentIssueArticlesBackgroundImageView.hidden = true
}
return cell
}
JSON-parsing code:
func populateCurrentIssue() {
if populatingCurrentIssue {
return
}
populatingCurrentIssue = true
self.cellLoadingIndicator.backgroundColor = goldenWordsYellow
self.cellLoadingIndicator.startAnimating()
Alamofire.request(GWNetworking.Router.Issue).responseJSON() { response in
if let JSON = response.result.value {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
var nodeIDArray : [Int]
if (JSON .isKindOfClass(NSDictionary)) {
for node in JSON as! Dictionary<String, AnyObject> {
let nodeIDValue = node.0
var lastItem : Int = 0
self.nodeIDArray.addObject(nodeIDValue)
if let issueElement : IssueElement = IssueElement(title: "Could not retrieve title", nodeID: 0, timeStamp: 0, imageURL: "init", author: "Author not found", issueNumber: "Issue # error", volumeNumber: "Volume # error", articleContent: "Could not retrieve article content", coverImageInteger: "init", coverImage: UIImage()) {
issueElement.title = node.1["title"] as! String
issueElement.nodeID = Int(nodeIDValue)!
let timeStampString = node.1["revision_timestamp"] as! String
issueElement.timeStamp = Int(timeStampString)!
issueElement.imageURL = String(node.1["image_url"])
if let author = node.1["author"] as? String {
issueElement.author = author
}
if let issueNumber = node.1["issue_int"] as? String {
issueElement.issueNumber = issueNumber
}
if let volumeNumber = node.1["volume_int"] as? String {
issueElement.volumeNumber = volumeNumber
}
if let articleContent = node.1["html_content"] as? String {
issueElement.articleContent = articleContent
}
issueElement.coverImageInteger = String(node.1["cover_image"]) // addition specific to the Current Issue View Controller
lastItem = self.currentIssueObjects.count
print(issueElement.nodeID)
if issueElement.articleContent.characters.count > 40 {
self.currentIssueObjects.addObject(issueElement)
print(issueElement.nodeID)
}
// Sorting with decreasing timestamp from top to bottom.
let timestampSortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
self.currentIssueObjects.sortUsingDescriptors([timestampSortDescriptor])
// Placing the object with coverImage
let coverImageSortDescriptor = NSSortDescriptor(key: "coverImageInteger", ascending: false)
self.currentIssueObjects.sortUsingDescriptors([coverImageSortDescriptor])
let indexPaths = (lastItem..<self.currentIssueObjects.count).map {
NSIndexPath(forItem: $0, inSection: 0) }
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.currentIssueTableView.reloadData()
self.cellLoadingIndicator.stopAnimating()
self.cellLoadingIndicator.hidesWhenStopped = true
}
}
}
self.populatingCurrentIssue = false
}
}