iOS app is crashing on scroll while fetching data from API - ios

I have used tableView to show the post and when I am scrolling my page sometimes it crashes and throws error as: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (119) must be equal to the number of rows contained in that section before the update (105), plus or minus the number of rows inserted or deleted from that section (1 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).' I am unable to find out the reason why it's happening
func getFeeds(){
DispatchQueue.main.async {
if(self.isCommentsOpened == false && self.spinner == nil && !self.isPaginating && self.isScrollingUp == false){
self.spinner = CommonUtils.showLoader(view: self)
}
}
var paramsDictionary = [String:Any]()
let xAuthToken:String=UserDefaults.standard.string(forKey: JsonContants.X_AUTH_TOKEN)!
let entityId:String=UserDefaults.standard.string(forKey: JsonContants.ENTITY_ID)!
var apiUrl=domains.global+Apis.feedQueryApi
apiUrl=apiUrl.replacingOccurrences(of: "{entity_id}", with: entityId)
if(isPaginating && pageNo<totalPages){
paramsDictionary[JsonContants.PAGE_NO] = pageNo+1
paramsDictionary[JsonContants.PAGE_SIZE] = pageSize
}else{
paramsDictionary[JsonContants.PAGE_NO] = 1
paramsDictionary[JsonContants.PAGE_SIZE] = pageSize
}
HttpClientApi.instance().makeAPICall(token: xAuthToken,refreshToken: "",url: apiUrl, params:paramsDictionary, method: .POST, success: { (data, response, error) in
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
let httpStatus=response as HTTPURLResponse!
let statusCode=httpStatus?.statusCode
let pageDetails = json[JsonContants.PAGE_DETAILS] as! [String:Any]
if(pageDetails.count>0){
self.pageNo = pageDetails[JsonContants.PAGE_NO] as! Int
self.pageSize = pageDetails[JsonContants.PAGE_SIZE] as! Int
self.totalPages = pageDetails[JsonContants.TOTAL_PAGES] as! Int
}
let feedsArray = json[JsonContants.FEEDS] as! Array<Dictionary<String, Any>>
if(!self.isPaginating){
self.feedsJsonArray = feedsArray
self.feedIdsArray = [String]()
self.feedIdUserIdDict = [String:String]()
self.userIdUserJsonDict = [String:[String:Any]]()
self.imagesJsonArray = []
self.feedIdActivityJsonDict = [String:[[String:Any]]]()
}else{
self.paginationFeedIdsArray = [String]()
self.feedsJsonArray.append(contentsOf: feedsArray)
}
var paginationUserIdDict = [String]()
for object:Dictionary<String,Any> in feedsArray{
let feedId=object[JsonContants.FEED_ID] as? String
self.feedIdsArray.append(feedId!)
let userId = object[JsonContants.USER_ID] as? String
self.feedIdUserIdDict[feedId!] = userId
if(self.isPaginating){
paginationUserIdDict.append(userId!)
self.paginationFeedIdsArray.append(feedId!)
}
}
DispatchQueue.main.async {
if(!self.isPaginating){
self.getUserList(userIds: Array(self.feedIdUserIdDict.values))
self.dismissLoader()
}else{
self.getUserList(userIds: paginationUserIdDict)
self.dismissLoader()
}
}
}
} catch let error {
print(error.localizedDescription)
DispatchQueue.main.async {
if(self.spinner != nil){
self.spinner!.dismissLoader()
self.spinner = nil
}
if((self.topScrollSpinnerContainerView.isHidden == false) || (self.downScrollSpinnerContainerView.isHidden == false)){
self.scrollSpinner!.dismissLoader2()
self.topScrollSpinnerContainerView.isHidden = true
self.downScrollSpinnerContainerView.isHidden = true
}
}
}
}, failure: { (data, response, error) in
DispatchQueue.main.async {
if(self.spinner != nil){
self.spinner!.dismissLoader()
self.spinner = nil
}
if((self.topScrollSpinnerContainerView.isHidden == false) || (self.downScrollSpinnerContainerView.isHidden == false)){
self.scrollSpinner!.dismissLoader2()
self.topScrollSpinnerContainerView.isHidden = true
self.downScrollSpinnerContainerView.isHidden = true
}
}
print(error?.localizedDescription as Any)
})
}
func showSmallLoaderAtBottom(view: UIView) -> UIView {
var spinnerView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height:50))
let spinner = MDCActivityIndicator(frame: CGRect(x: 0, y: 0, width: 50, height:50))
spinner.cycleColors = [UIColor(named: AppColors.appSkyBlue.rawValue)!, UIColor(named: AppColors.appSkyBlue.rawValue)!,UIColor(named: AppColors.appSkyBlue.rawValue)!,UIColor(named: AppColors.appSkyBlue.rawValue)!]
spinnerView.addSubview(spinner)
view.addSubview(spinnerView)
spinner.startAnimating()
return spinnerView
}
func getMoreData(){
if(self.pageNo < self.totalPages){
scrollSpinner = showSmallLoaderAtBottom(view: downScrollSpinnerContainerView)
downScrollSpinnerContainerView.isHidden = false
isPaginating = true
self.getFeeds()
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
self.currentRow = indexPath.row
let cell=tableView.dequeueReusableCell(withIdentifier: "feed_tvcell", for: indexPath) as! FeedTableViewCell
cell.selectionStyle = .none
cell.feedViewController = self
cell.feedsStackView.translatesAutoresizingMaskIntoConstraints = false
let feedJson = self.feedsJsonArray[indexPath.row]
cell.messageTextLabel.numberOfLines = 0
cell.messageTextLabel.lineBreakMode = .byWordWrapping
cell.messageTextLabel.sizeToFit()
if(feedJson[JsonContants.CONTENT] != nil && !(feedJson[JsonContants.CONTENT] as! String).elementsEqual(JsonContants.NA)){
cell.feedMessageView.isHidden = false
cell.messageTextLabel.text = (feedJson[JsonContants.CONTENT] as! String).decodeEmoji
}else{
cell.feedMessageView.isHidden = true
}
let feedId = feedJson[JsonContants.FEED_ID] as! String
let userId = feedIdUserIdDict[feedId] as! String
let userJson = userIdUserJsonDict[userId] as? [String:Any]
var userTitle:[[String:Any]]?
var lastName:String?
var firstName:String?
if(userJson != nil){
userTitle = userJson![JsonContants.USER_TITLE] as? [[String:Any]]
lastName = userJson![JsonContants.LAST_NAME] as? String
firstName = userJson![JsonContants.FIRST_NAME] as? String
}
var roles = self.appDefaults.value(forKey: JsonContants.ROLE) as! [String]
if(firstName != nil){
cell.feeUserName.text = (firstName as! String)
}
if(lastName != nil){
cell.feeUserName.text = cell.feeUserName.text!+" "+(lastName as! String)
}
hideAndShowFeedDeleteButton(roles, cell, userId)
addActionTargetsToCellButtons(cell)
var time = feedJson[JsonContants.LAST_ACTIVITY_TIME] as! Int64
var timeDiff = CommonUtils.getSystemTimeInMillis() - time
cell.feedTime.text = CommonUtils.getStringValueOfTimeDiff(timeDiff: timeDiff)
setCountZero(cell)
setLikeCount(feedId, cell, feedJson)
var feedType = feedJson[JsonContants.TYPE] as! String
let feedCommentCount = feedJson[JsonContants.FEED_COMMENT_COUNT] as! Int
cell.commentCountLabel.text = String(feedCommentCount)
if(userJson != nil){
let userId = userJson![JsonContants.USER_ID] as? String
var cachedMediaId:UIImage?
let userJsonFromDb = CoreDataDatabaseManager.coreDataDatabaseManager.getUser(id: userId!)
if(userJsonFromDb != nil && userJsonFromDb.count>0){
let imageId = userJsonFromDb[JsonContants.IMAGE_ID] as? String
if(userId != nil && imageId != nil){
cachedMediaId = self.getSavedImage(named : imageId!+"."+"png")
}
}
if(cachedMediaId == nil){
cell.feedUserImage.image = #imageLiteral(resourceName: "user_default_round")
getUserImages(userIds: [userId!],cell: cell)
}else{
cell.feedUserImage.image = cachedMediaId
}
}else{
cell.feedUserImage.image = #imageLiteral(resourceName: "user_default_round")
}
if(userJson != nil && userJson![JsonContants.RESIDENT_DETAILS] != nil){
let residentDetails = userJson![JsonContants.RESIDENT_DETAILS] as! [String:Any]
let buildingName = residentDetails[JsonContants.BUILDING_NAME] as! String
let flatName = residentDetails[JsonContants.FLAT_NAME] as! String
let feedUserName:String = cell.feeUserName.text!
if(buildingName.count>0 && flatName.count>0){
cell.feeUserName.text = feedUserName+" - "+buildingName+"("+flatName+")"
}
}else if(userTitle != nil && userTitle!.count>0) {
let titleDict = userTitle![0]
let name = cell.feeUserName.text
if(titleDict.count>0){
var title = titleDict[JsonContants.TITLE] as! String
if(title.elementsEqual(JsonContants.ADMINISTRATOR)){
cell.feeUserName.text = name!+" - "+"Admin"
}
}
}
if(feedType.elementsEqual(JsonContants.SURVEY)){
let options = feedJson[JsonContants.OPTIONS] as! [[String:Any]]
setSurveyData(cell, options, feedId, feedJson,indexPath: indexPath)
}else{
if(feedJson[JsonContants.MEDIA_INFO] != nil && (feedJson[JsonContants.MEDIA_INFO] as! [String:Any]) != nil &&
(feedJson[JsonContants.MEDIA_INFO] as! [String:Any]).count>0){
let mediaJson = feedJson[JsonContants.MEDIA_INFO] as! [String:Any]
let mediaType = mediaJson[JsonContants.MEDIA_TYPE] as! String
cell.optionsTableView.isHidden = true
cell.surveyTotalVotesLabel.isHidden = true
cell.surveyTotalVotesLabelContainer.isHidden = true
cell.feedVideoView.isHidden = true
cell.feedImageView.isHidden = true
if(mediaType.elementsEqual(JsonContants.IMAGE)){
configureFeedImageViewAndSetImage(cell, mediaJson, feedId,indexPath)
}else{
configureFeedMediaViewAndSetVideo(cell, mediaJson, indexPath)
}
}else{
cell.mediaType = "TEXT"
hideFeedMediaViews(cell)
cell.layoutIfNeeded()
}
}
if(indexPath.row == (self.feedsJsonArray.count-2)){
DispatchQueue.main.async{
self.getMoreData()
}
}
cell.layoutIfNeeded()
return cell
}

This kind of error is seen when you explicitly insert or delete cells or sections into or from a TableView and do not simultaneously readjust your row or section counts to match. In your case the error message is telling you exactly what the count mismatch is. The code you posted is not showing any inserts or deletes of rows from the TableView so it must be happening somewhere else in your code, maybe in your getFeeds() method?

Related

Adding data to a particular table in CoreData in iOS Swift

I am using CoreData in my project and I am successfully able to save data in my tables and display. I am also able to update the existing Data. but I am not able to add a new data to a particular table.
The table relation is WorkOrderData--> one to many with WorkOrderTaskAsset and WorkOrderTaskAsset --> one to many with condition.
If I have to add a condition Object on some button click. I am not getting how to add it. I tried to create a Condition Object and add it. But I am getting error
.Condition setLabel:]: unrecognized selector sent to instance 0x600000077540'
func saveDataInCoreData(jsonArray : NSArray) {
for orders in jsonArray{
let WorkOrderDataClassName:String = String(describing: WorkOrderData.self)
let workOrderData:WorkOrderData = NSEntityDescription.insertNewObject(forEntityName: WorkOrderDataClassName, into: DatabaseController.getContext()) as! WorkOrderData
let ContractorClassName:String = String(describing: Contractor.self)
let contractor:Contractor = NSEntityDescription.insertNewObject(forEntityName: ContractorClassName, into: DatabaseController.getContext()) as! Contractor
let StatusClassName:String = String(describing: Status.self)
let status:Status = NSEntityDescription.insertNewObject(forEntityName: StatusClassName, into: DatabaseController.getContext()) as! Status
let order = orders as! NSDictionary
// Work Order Parsing
workOrderData.workOrderNo = order["workOrderNo"]! as? String
if order["description"] != nil {
workOrderData.descriptin = order["description"]! as? String
}
if order["comments"] != nil {
workOrderData.comments = order["comments"]! as? String
}
let desCodeId = order["descriptionCodeID"]! as? Int
if desCodeId != nil {
workOrderData.descriptionCodeID = Int16(UInt16(desCodeId!))
}
if order["definition"] != nil {
workOrderData.definition = order["definition"]! as? String
}
let priortyID = order["priorityID"]! as? Int
if priortyID != nil {
workOrderData.priorityID = Int16(UInt16(desCodeId!))
}
let numbrOfAssets = order["numberofAssests"]! as? Int
if numbrOfAssets != nil {
workOrderData.numberofAssests = Int16(UInt16(numbrOfAssets!))
}
if order["generatedDateTime"] != nil {
workOrderData.generatedDateTime = (order["generatedDateTime"]! as? Double)!
}
if order["initiatedBy"] != nil {
workOrderData.initiatedBy = order["initiatedBy"]! as? String
}
if order["generatedBy"] != nil {
workOrderData.generatedBy = order["generatedBy"]! as? String
}
if order["issueDate"] != nil {
workOrderData.issueDate = (order["issueDate"]! as? Double)!
}
if order["finishDate"] != nil {
workOrderData.finishDate = (order["finishDate"]! as? Double)!
}
if order["statusID"] != nil {
let statsID = order["statusID"]! as? Int
workOrderData.statusID = Int16(UInt16(statsID!))
}
if order["assigneeID"] != nil {
let assigneID = order["assigneeID"]! as? Int
workOrderData.assigneeID = Int16(UInt16(assigneID!))
}
if order["updateDate"] != nil {
let updatDate = order["updateDate"]! as? Double
workOrderData.updateDate = updatDate!
}
if order["startDate"] != nil {
workOrderData.startDate = (order["startDate"]! as? Double)!
}
if order["proceedDate"] != nil {
workOrderData.proceedDate = (order["proceedDate"]! as? Double)!
}
if order["createDate"] != nil {
workOrderData.createDate = (order["createDate"]! as? Double)!
}
if order["inclementDays"] != nil {
let inclemntDays = order["inclementDays"]! as? Int
workOrderData.inclementDays = Int16(UInt16(inclemntDays!))
}
if order["totalHydrantsPainted"] != nil {
let totalHydrantPainted = order["totalHydrantsPainted"]! as? Int
workOrderData.totalHydrantsPainted = Int16(UInt16(totalHydrantPainted!))
}
if order["totalHydrantsNotPainted"] != nil {
let totalHydrantNotPainted = order["totalHydrantsNotPainted"]! as? Int
workOrderData.totalHydrantsNotPainted = Int16(UInt16(totalHydrantNotPainted!))
}
if order["contractorId"] != nil {
let contractrId = order["contractorId"]! as? Int
workOrderData.contractorId = Int16(UInt16(contractrId!))
}
// Contractor Started
let contractorDict = order["contractor"]! as? NSDictionary
if contractorDict?["id"] != nil {
let contrctrId = contractorDict?["id"]! as? Int
contractor.id = Int16(UInt16(contrctrId!))
}
contractor.name = contractorDict?["name"]! as? String
contractor.email = contractorDict?["email"]! as? String
contractor.label = contractorDict?["label"]! as? String
contractor.purchaseOrderNumber = contractorDict?["purchaseOrderNumber"]! as? String
contractor.vendorId = contractorDict?["vendorId"]! as? String
workOrderData.contractor = contractor
if order["status"] != nil {
let statusDict = order["status"]! as? NSDictionary
let statusId = statusDict?["id"]! as? Int
if statusId != nil {
status.id = Int16(UInt16(statusId!))
}
status.label = statusDict?["label"]! as? String
status.descriptin = statusDict?["description"]! as? String
status.rule = statusDict?["rule"]! as? String
workOrderData.status = status
}
// Inclement Work Order Started
if order["workOrderInclementWeatherDates"] != nil {
let workOrderInclementWeatherDate = order["workOrderInclementWeatherDates"] as! [NSDictionary]
if workOrderInclementWeatherDate.count > 0 {
let setArray = NSMutableArray()
let set = NSMutableSet()
for inclementItem in workOrderInclementWeatherDate {
let WorkOrderInclementWeatherDatesClassName:String = String(describing: WorkOrderInclementWeatherDates.self)
let workOrderInclementWeatherDates:WorkOrderInclementWeatherDates = NSEntityDescription.insertNewObject(forEntityName: WorkOrderInclementWeatherDatesClassName, into: DatabaseController.getContext()) as! WorkOrderInclementWeatherDates
workOrderInclementWeatherDates.createTimeStamp = inclementItem.value(forKey: "createTimeStamp") as! Double
workOrderInclementWeatherDates.inclementDate = inclementItem.value(forKey: "inclementDate") as! Double
workOrderInclementWeatherDates.workOrderNo = inclementItem.value(forKey: "workOrderNo") as? String
setArray.add(workOrderInclementWeatherDates)
set.add(workOrderInclementWeatherDates)
}
workOrderData.addToWorkOrderInclementWeather(set as NSSet)
}
}
// Task List
// Inclement Work Order Started
if order["workOrderTask"] != nil {
let workOrderTaskArray = order["workOrderTask"] as! [NSDictionary]
if workOrderTaskArray.count > 0 {
let workOrderSet = NSMutableSet()
for workOrderItem in workOrderTaskArray {
let WorkOrderTaskClassName:String = String(describing: WorkOrderTask.self)
let workOrderTask:WorkOrderTask = NSEntityDescription.insertNewObject(forEntityName: WorkOrderTaskClassName, into: DatabaseController.getContext()) as! WorkOrderTask
workOrderTask.woTaskDescription = workOrderItem.value(forKey: "woTaskDescription") as? String
workOrderTask.taskStatus = workOrderItem.value(forKey: "taskStatus") as? String
if workOrderItem["projectedStartDate"] != nil {
workOrderTask.projectedStartDate = workOrderItem.value(forKey: "projectedStartDate") as! Double
}
if workOrderItem["actualStartDate"] != nil {
workOrderTask.actualStartDate = workOrderItem.value(forKey: "actualStartDate") as! Double
}
if workOrderItem["taskNumber"] != nil {
let taskNumber = workOrderItem["taskNumber"]! as? Int
workOrderTask.taskNumber = Int16(UInt16(taskNumber!))
}
if workOrderItem["noOfHydrantsCompleted"] != nil {
let noOfHydrantsCompleted = workOrderItem["noOfHydrantsCompleted"]! as? Int
workOrderTask.noOfHydrantsCompleted = Int16(UInt16(noOfHydrantsCompleted!))
}
if workOrderItem["noOfHydrantsPending"] != nil {
let noOfHydrantsPending = workOrderItem["noOfHydrantsPending"]! as? Int
workOrderTask.noOfHydrantsPending = Int16(UInt16(noOfHydrantsPending!))
}
workOrderSet.add(workOrderTask)
}
workOrderData.addToWorkOrdertask(workOrderSet as NSSet)
}
}
// workOrderTaskAsstDetails
if order["workOrderTaskAsstDetails"] != nil {
let workOrderTaskAsstDetailsDict = order["workOrderTaskAsstDetails"] as! [NSDictionary]
if workOrderTaskAsstDetailsDict.count > 0 {
let set = NSMutableSet()
for workOrderTaskAsstDetailsItem in workOrderTaskAsstDetailsDict {
let WorkOrderTaskAsstDetailsClassName:String = String(describing: WorkOrderTaskAsstDetails.self)
let workOrderTaskAsstDetails:WorkOrderTaskAsstDetails = NSEntityDescription.insertNewObject(forEntityName: WorkOrderTaskAsstDetailsClassName, into: DatabaseController.getContext()) as! WorkOrderTaskAsstDetails
let woTaskAsstId = workOrderTaskAsstDetailsItem["woTaskAsstId"]! as? Int
if woTaskAsstId != nil {
workOrderTaskAsstDetails.woTaskAsstId = Int16(UInt16(woTaskAsstId!))
}
workOrderTaskAsstDetails.woTaskNo = workOrderTaskAsstDetailsItem.value(forKey: "woTaskNo") as? String
workOrderTaskAsstDetails.assetId = workOrderTaskAsstDetailsItem.value(forKey: "assetId") as? String
workOrderTaskAsstDetails.descripton = workOrderTaskAsstDetailsItem.value(forKey: "description") as? String
workOrderTaskAsstDetails.statusID = workOrderTaskAsstDetailsItem.value(forKey: "statusID") as? String
if workOrderTaskAsstDetailsItem["projectedStartDate"] != nil {
workOrderTaskAsstDetails.projectedStartDate = (workOrderTaskAsstDetailsItem["projectedStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualStartDate"] != nil {
workOrderTaskAsstDetails.actualStartDate = (workOrderTaskAsstDetailsItem["actualStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["projectedCompleteDate"] != nil {
workOrderTaskAsstDetails.projectedCompleteDate = (workOrderTaskAsstDetailsItem["projectedCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualCompleteDate"] != nil {
workOrderTaskAsstDetails.actualCompleteDate = (workOrderTaskAsstDetailsItem["actualCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["lastPaintedDate"] != nil {
workOrderTaskAsstDetails.lastPaintedDate = (workOrderTaskAsstDetailsItem["lastPaintedDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["workOrderStartDate"] != nil {
workOrderTaskAsstDetails.workOrderStartDate = (workOrderTaskAsstDetailsItem["workOrderStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["createDate"] != nil {
workOrderTaskAsstDetails.createDate = (workOrderTaskAsstDetailsItem["createDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["updateDate"] != nil {
workOrderTaskAsstDetails.updateDate = (workOrderTaskAsstDetailsItem["updateDate"]! as? Double)!
}
workOrderTaskAsstDetails.workOrderNumber = workOrderTaskAsstDetailsItem.value(forKey: "workOrderNumber") as? String
workOrderTaskAsstDetails.beforePicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLatitude") as? String
workOrderTaskAsstDetails.beforePicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLongitude") as? String
workOrderTaskAsstDetails.afterPicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLatitude") as? String
workOrderTaskAsstDetails.afterPicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLongitude") as? String
let transactionType = workOrderTaskAsstDetailsItem["transactionType"]! as? Int
if transactionType != nil {
workOrderTaskAsstDetails.transactionType = Int16(UInt16(transactionType!))
}
let assetValid = workOrderTaskAsstDetailsItem["assetValid"]! as? Int
if assetValid != nil {
workOrderTaskAsstDetails.assetValid = Int16(UInt16(assetValid!))
}
//Asset
let AssetClassName:String = String(describing: Asset.self)
let asset:Asset = NSEntityDescription.insertNewObject(forEntityName: AssetClassName, into: DatabaseController.getContext()) as! Asset
let assetDict = workOrderTaskAsstDetailsItem["asset"]! as? NSDictionary
asset.descripton = assetDict?["description"]! as? String
asset.type = assetDict?["type"]! as? String
asset.assetId = assetDict?["assetId"]! as? String
if assetDict?["asset200ft"] != nil {
asset.asset200ft = assetDict?["asset200ft"]! as? String
}
if assetDict?["streetNumber"] != nil{
asset.streetNumber = assetDict?["streetNumber"]! as? String
}
asset.county = assetDict?["county"]! as? String
asset.latitude = assetDict?["latitude"]! as? String
asset.longitude = assetDict?["longitude"]! as? String
workOrderTaskAsstDetails.asset = asset
//Condition
if workOrderTaskAsstDetailsItem["assetConditions"] != nil{
let conditionDict = workOrderTaskAsstDetailsItem["assetConditions"] as! [NSDictionary]
if conditionDict.count > 0{
let conditinSet = NSMutableSet()
for assetConditionsDetailsDict in conditionDict {
let ConditionClassName:String = String(describing: Condition.self)
let condition:Condition = NSEntityDescription.insertNewObject(forEntityName: ConditionClassName, into: DatabaseController.getContext()) as! Condition
let assetConditionItem = assetConditionsDetailsDict["condition"] as! NSDictionary
condition.id = assetConditionItem["id"]as? String
condition.label = assetConditionItem["label"]as? String
condition.rule = assetConditionItem["rule"]as? String
condition.descriptin = assetConditionItem["description"]as? String
conditinSet.add(condition)
}
workOrderTaskAsstDetails.addToCondition(conditinSet as NSSet)
}
}
set.add(workOrderTaskAsstDetails)
}
workOrderData.addToWorkOrderTaskAsstDetails(set as NSSet)
}
}
// assetList
if order["assetList"] != nil {
let workOrderTaskAsstDetailsDict = order["assetList"] as! [NSDictionary]
if workOrderTaskAsstDetailsDict.count > 0 {
let set = NSMutableSet()
for workOrderTaskAsstDetailsItem in workOrderTaskAsstDetailsDict {
let WorkOrderTaskAsstDetailsClassName:String = String(describing: AssetList.self)
let workOrderTaskAsstDetails:AssetList = NSEntityDescription.insertNewObject(forEntityName: WorkOrderTaskAsstDetailsClassName, into: DatabaseController.getContext()) as! AssetList
let woTaskAsstId = workOrderTaskAsstDetailsItem["woTaskAsstId"]! as? Int
if woTaskAsstId != nil {
workOrderTaskAsstDetails.woTaskAsstId = Int16(UInt16(woTaskAsstId!))
}
workOrderTaskAsstDetails.woTaskNo = workOrderTaskAsstDetailsItem.value(forKey: "woTaskNo") as? String
workOrderTaskAsstDetails.assetId = workOrderTaskAsstDetailsItem.value(forKey: "assetId") as? String
workOrderTaskAsstDetails.descripton = workOrderTaskAsstDetailsItem.value(forKey: "description") as? String
workOrderTaskAsstDetails.statusID = workOrderTaskAsstDetailsItem.value(forKey: "statusID") as? String
if workOrderTaskAsstDetailsItem["projectedStartDate"] != nil {
workOrderTaskAsstDetails.projectedStartDate = (workOrderTaskAsstDetailsItem["projectedStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualStartDate"] != nil {
workOrderTaskAsstDetails.actualStartDate = (workOrderTaskAsstDetailsItem["actualStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["projectedCompleteDate"] != nil {
workOrderTaskAsstDetails.projectedCompleteDate = (workOrderTaskAsstDetailsItem["projectedCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualCompleteDate"] != nil {
workOrderTaskAsstDetails.actualCompleteDate = (workOrderTaskAsstDetailsItem["actualCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["lastPaintedDate"] != nil {
workOrderTaskAsstDetails.lastPaintedDate = (workOrderTaskAsstDetailsItem["lastPaintedDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["workOrderStartDate"] != nil {
workOrderTaskAsstDetails.workOrderStartDate = (workOrderTaskAsstDetailsItem["workOrderStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["createDate"] != nil {
workOrderTaskAsstDetails.createDate = (workOrderTaskAsstDetailsItem["createDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["updateDate"] != nil {
workOrderTaskAsstDetails.updateDate = (workOrderTaskAsstDetailsItem["updateDate"]! as? Double)!
}
workOrderTaskAsstDetails.workOrderNumber = workOrderTaskAsstDetailsItem.value(forKey: "workOrderNumber") as? String
workOrderTaskAsstDetails.beforePicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLatitude") as? String
workOrderTaskAsstDetails.beforePicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLongitude") as? String
workOrderTaskAsstDetails.afterPicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLatitude") as? String
workOrderTaskAsstDetails.afterPicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLongitude") as? String
let transactionType = workOrderTaskAsstDetailsItem["transactionType"]! as? Int
if transactionType != nil {
workOrderTaskAsstDetails.transactionType = Int16(UInt16(transactionType!))
}
let assetValid = workOrderTaskAsstDetailsItem["assetValid"]! as? Int
if assetValid != nil {
workOrderTaskAsstDetails.assetValid = Int16(UInt16(assetValid!))
}
//Asset
let AssetClassName:String = String(describing: AssetListAsset.self)
let asset:AssetListAsset = NSEntityDescription.insertNewObject(forEntityName: AssetClassName, into: DatabaseController.getContext()) as! AssetListAsset
let assetDict = workOrderTaskAsstDetailsItem["asset"]! as? NSDictionary
asset.descripton = assetDict?["description"]! as? String
asset.type = assetDict?["type"]! as? String
asset.assetId = assetDict?["assetId"]! as? String
if assetDict?["asset200ft"] != nil {
asset.asset200ft = assetDict?["asset200ft"]! as? String
}
if assetDict?["streetNumber"] != nil{
asset.streetNumber = assetDict?["streetNumber"]! as? String
}
asset.county = assetDict?["county"]! as? String
asset.latitude = assetDict?["latitude"]! as? String
asset.longitude = assetDict?["longitude"]! as? String
workOrderTaskAsstDetails.assetListAsset = asset
//Condition
if workOrderTaskAsstDetailsItem["assetConditions"] != nil{
let conditionDict = workOrderTaskAsstDetailsItem["assetConditions"] as! [NSDictionary]
if conditionDict.count > 0{
let conditinSet = NSMutableSet()
for assetConditionsDetailsDict in conditionDict {
let ConditionClassName:String = String(describing: AssetListCondition.self)
let condition:AssetListCondition = NSEntityDescription.insertNewObject(forEntityName: ConditionClassName, into: DatabaseController.getContext()) as! AssetListCondition
let assetConditionItem = assetConditionsDetailsDict["condition"] as! NSDictionary
condition.id = assetConditionItem["id"]as? String
condition.label = assetConditionItem["label"]as? String
condition.rule = assetConditionItem["rule"]as? String
condition.descriptin = assetConditionItem["description"]as? String
conditinSet.add(condition)
}
workOrderTaskAsstDetails.addToAssetListCondition(conditinSet as NSSet)
}
}
set.add(workOrderTaskAsstDetails)
}
workOrderData.addToAssetList(set as NSSet)
}
}
DatabaseController.saveContext()
}
fetchFrmDB()
}
the code include other table also which I have not shown in pic
Please help me.. Thanks in Advance

Some cells won't show

I'm trying to create a chat applications with tableview to show the messages. Everything works fine except that some cells just won't show. It aren't always the same cells. I'm getting the messages from my Firebase database.
My Code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = cellCache.object(forKey: indexPath as AnyObject) as? UITableViewCell{
return cell
}
let cell = messagesTableView.dequeueReusableCell(withIdentifier: "otherMessageCell") as! OtherMessageTableViewCell
DispatchQueue.global(qos: .userInteractive).async {
let message = self.messages[indexPath.row]
let ref = FIRDatabase.database().reference()
let uid = FIRAuth.auth()?.currentUser?.uid
if(uid == message.sender) {
cell.sender.textAlignment = .right
cell.message.textAlignment = .right
}else{
cell.sender.textAlignment = .left
cell.message.textAlignment = .left
}
let uidReference = ref.child("Users").child(message.sender!)
uidReference.observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let username = dictionary["Username"] as! String
let imageLink = dictionary["Image Link"] as! String
cell.sender.text = username
cell.message.text = message.message
cell.profileImage.image = nil
cell.profileImage.loadImageWithURLString(urlString: imageLink)
}
}, withCancel: nil)
}
DispatchQueue.main.async {
self.cellCache.setObject(cell, forKey: indexPath as AnyObject)
}
return cell
}
Example:
I hope someone will be able to help me. Thanks
I've found a solution:
var savedSenders = [Int: String]()
var savedMessages = [Int: String]()
var savedImages = [Int: UIImage]()
var savedAlignments = [Int: NSTextAlignment]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = messagesTableView.dequeueReusableCell(withIdentifier: "otherMessageCell") as! OtherMessageTableViewCell
if(savedSenders[indexPath.row] != nil && savedMessages[indexPath.row] != nil && savedImages[indexPath.row] != nil && savedAlignments[indexPath.row] != nil) {
cell.sender.textAlignment = savedAlignments[indexPath.row]!
cell.message.textAlignment = savedAlignments[indexPath.row]!
cell.sender.text = savedSenders[indexPath.row]
cell.message.text = savedMessages[indexPath.row]
cell.profileImage.image = savedImages[indexPath.row]
return cell
}
cell.sender.text = ""
cell.message.text = ""
cell.profileImage.image = nil
DispatchQueue.global(qos: .userInteractive).async {
let message = self.messages[indexPath.row]
let ref = FIRDatabase.database().reference()
let uid = FIRAuth.auth()?.currentUser?.uid
if(uid == message.sender) {
cell.sender.textAlignment = .right
cell.message.textAlignment = .right
self.savedAlignments.updateValue(.right, forKey: indexPath.row)
}else{
cell.sender.textAlignment = .left
cell.message.textAlignment = .left
self.savedAlignments.updateValue(.left, forKey: indexPath.row)
}
let uidReference = ref.child("Users").child(message.sender!)
uidReference.observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let username = dictionary["Username"] as! String
let imageLink = dictionary["Image Link"] as! String
cell.sender.text = username
cell.message.text = message.message
cell.profileImage.image = nil
cell.profileImage.loadImageWithURLString(urlString: imageLink)
let url = URL(string: imageLink)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if(error != nil){
print(error as Any)
return
}
DispatchQueue.main.async {
if let downloadedImage = UIImage(data: data!) {
let image = downloadedImage
self.savedSenders.updateValue(username, forKey: indexPath.row)
self.savedMessages.updateValue(message.message!, forKey: indexPath.row)
self.savedImages.updateValue(image, forKey: indexPath.row)
}
}
}.resume()
}
}, withCancel: nil)
}
return cell
}
The data for every cell is saved into the arrays (savedSenders, savedMessages, savedImages and savedAlignments). If I don't save it into arrays, the cells will have to load all the data from Firebase and this will take longer. If it takes longer, it won't look good.
I tested everything and it works.

Collection View displays duplicates on refresh and then deletes them

I'm working with a collectionView right now and when I activate the refresh control, it adds a duplicate picture to the data source set for every picture in the set, and then makes it disappear and things go back to normal by the time the refresh control is done. Here's a YouTube video I uploaded to clearly show you what is going on.
https://youtu.be/Q9ZFd-7tSRw
It would seem logical that the data source set would be getting the same data from the API I am using, then displaying it, the duplicate data then getting deleting from the array, and then the collection view being reloaded once more before the refresh control goes away. That's not how I want it to work obviously, but perhaps I have coded it wrong.
viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.registerClass(PhotoBrowserCollectionViewCell.self, forCellWithReuseIdentifier: PhotoBrowserCellIdentifier)
self.cellLoadingIndicator.backgroundColor = goldenWordsYellow
self.cellLoadingIndicator.hidesWhenStopped = true
if self.revealViewController() != nil {
revealViewControllerIndicator = 1
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
self.revealViewController().rearViewRevealWidth = 280
collectionView!.delegate = self
collectionView!.dataSource = self
goldenWordsRefreshControl = UIRefreshControl()
goldenWordsRefreshControl.backgroundColor = goldenWordsYellow
goldenWordsRefreshControl.tintColor = UIColor.whiteColor()
self.collectionView!.addSubview(goldenWordsRefreshControl)
navigationController?.setNavigationBarHidden(false, animated: true)
navigationItem.title = "Pictures"
setupView()
populatePhotos()
self.dateFormatter.dateFormat = "dd/MM/yy"
self.cellLoadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
self.cellLoadingIndicator.color = goldenWordsYellow
self.cellLoadingIndicator.center = (self.collectionView?.center)!
self.collectionView!.addSubview(cellLoadingIndicator)
self.collectionView!.bringSubviewToFront(cellLoadingIndicator)
/*
self.dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
self.dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
let currentDateAndTime = NSDate()
let updateString = "Last updated at " + self.dateFormatter.stringFromDate(currentDateAndTime)
self.goldenWordsRefreshControl.attributedTitle = NSAttributedString(string: updateString)
*/
}
populatePhotos:
func populatePhotos() {
if populatingPhotos {
return
}
populatingPhotos = true
self.cellLoadingIndicator.startAnimating()
self.temporaryPictureObjects.removeAllObjects()
Alamofire.request(GWNetworking.Router.Pictures(self.currentPage)).responseJSON() { response in
if let JSON = response.result.value {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 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 pictureElement : PictureElement = PictureElement(title: "Picture", nodeID: 0, timeStamp: 0, imageURL: "http://goldenwords.ca/sites/all/themes/custom/gw/logo.png", author: "Staff", issueNumber: "Issue # error", volumeNumber: "Volume # error") {
pictureElement.title = node.1["title"] as! String
pictureElement.nodeID = Int(nodeIDValue)!
let timeStampString = node.1["revision_timestamp"] as! String
pictureElement.timeStamp = Int(timeStampString)!
if let imageURL = node.1["image_url"] as? String {
pictureElement.imageURL = imageURL
}
if let author = node.1["author"] as? String {
pictureElement.author = author
}
if let issueNumber = node.1["issue_int"] as? String {
pictureElement.issueNumber = issueNumber
}
if let volumeNumber = node.1["volume_int"] as? String {
pictureElement.volumeNumber = volumeNumber
}
lastItem = self.temporaryPictureObjects.count // Using a temporary set to not handle the dataSource set directly (safer).
self.temporaryPictureObjects.addObject(pictureElement)
let indexPaths = (lastItem..<self.temporaryPictureObjects.count).map { NSIndexPath(forItem: $0, inSection: 0) }
}
}
/* Sorting the elements in order of newest to oldest (as the array index increases] */
let timeStampSortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
self.pictureObjects.sortUsingDescriptors([timeStampSortDescriptor])
}
dispatch_async(dispatch_get_main_queue()) {
self.pictureObjects = self.temporaryPictureObjects
self.collectionView!.reloadData()
self.cellLoadingIndicator.stopAnimating()
self.currentPage++
self.populatingPhotos = false
}
}
}
}
}
handleRefresh:
func handleRefresh() {
goldenWordsRefreshControl.beginRefreshing()
self.pictureObjects.removeAllObjects()
self.currentPage = 0
self.cellLoadingIndicator.startAnimating()
self.picturesCollectionView.bringSubviewToFront(cellLoadingIndicator)
self.populatingPhotos = false
populatePhotos()
self.cellLoadingIndicator.stopAnimating()
goldenWordsRefreshControl.endRefreshing()
}
cellForItemAtIndexPath:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCellIdentifier, forIndexPath: indexPath) as! PhotoBrowserCollectionViewCell
if let pictureObject = pictureObjects.objectAtIndex(indexPath.row) as? PictureElement {
let title = pictureObject.title ?? "" // if pictureObject.title == nil, then we return an empty string
let timeStampDateObject = NSDate(timeIntervalSince1970: NSTimeInterval(pictureObject.timeStamp))
let timeStampDateString = dateFormatter.stringFromDate(timeStampDateObject)
let author = pictureObject.author ?? ""
let issueNumber = pictureObject.issueNumber ?? ""
let volumeNumber = pictureObject.volumeNumber ?? ""
let nodeID = pictureObject.nodeID ?? 0
let imageURL = pictureObject.imageURL ?? "http://goldenwords.ca/sites/all/themes/custom/gw/logo.png"
cell.request?.cancel()
if let image = self.imageCache.objectForKey(imageURL) as? UIImage {
cell.imageView.image = image
} else {
cell.imageView.image = nil
cell.request = Alamofire.request(.GET, imageURL).responseImage() { response in
if let image = response.result.value {
self.imageCache.setObject(response.result.value!, forKey: imageURL)
if cell.imageView.image == nil {
cell.imageView.image = image
}
}
}
}
}
return cell
}

Missing return in a function expected to return 'UITableViewCell'

EDIT 1: Revised code - still does not work.
I've got two custom cells.
The first cell (and only the first cell) will be of type CurrentIssueFrontCoverTableViewCell, and the rest of the cells will be of type CurrentIssueArticlesTableViewCell. I am getting the error, described in the title, when declaring my cellForRowAtIndexPath function. Any idea of to fix this ? Why is it not detecting that I'm returning the cell in my "if" loop ?
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
let row = indexPath.row
if indexPath.row == 0 {
let cellWithCoverImage = tableView.dequeueReusableCellWithIdentifier(CurrentIssueFrontCoverTableCellIdentifier, forIndexPath: indexPath) as! CurrentIssueFrontCoverTableViewCell
if let currentIssueFrontCoverObject = currentIssueObjects.objectAtIndex(indexPath.row) as? IssueElement {
let title = currentIssueFrontCoverObject.title ?? ""
let timeStampDateObject = NSDate(timeIntervalSince1970: NSTimeInterval(currentIssueFrontCoverObject.timeStamp))
let timeStampDateString = dateFormatter.stringFromDate(timeStampDateObject)
let issueNumber = currentIssueFrontCoverObject.issueNumber ?? ""
let volumeNumber = currentIssueFrontCoverObject.volumeNumber ?? ""
let nodeID = currentIssueFrontCoverObject.nodeID ?? 0
let imageURL = currentIssueFrontCoverObject.imageURL ?? ""
cellWithCoverImage.request?.cancel()
if let coverImage = self.imageCache.objectForKey(imageURL) as? UIImage {
cellWithCoverImage.currentIssueFrontCoverImageView.image = coverImage
} else {
cellWithCoverImage.currentIssueFrontCoverImageView.image = nil
cellWithCoverImage.request = Alamofire.request(.GET, imageURL).responseImage() { response in
if let coverImage = response.result.value {
self.imageCache.setObject(response.result.value!, forKey: imageURL)
cellWithCoverImage.currentIssueFrontCoverImageView.image = coverImage
} else {
}
}
}
} else {
}
return cellWithCoverImage
// Populating data in the "Articles" type cells
} else if indexPath.row >= 1 {
let cellWithoutCoverImage = tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as! CurrentIssueArticlesTableViewCell
if let currentIssueArticleObject = currentIssueObjects.objectAtIndex(indexPath.row) as? IssueElement {
let title = currentIssueArticleObject.title ?? ""
let timeStampDateObject = NSDate(timeIntervalSince1970: NSTimeInterval(currentIssueArticleObject.timeStamp))
let timeStampDateString = dateFormatter.stringFromDate(timeStampDateObject)
let author = currentIssueArticleObject.author ?? ""
let issueNumber = currentIssueArticleObject.issueNumber ?? ""
let volumeNumber = currentIssueArticleObject.volumeNumber ?? ""
let articleContent = currentIssueArticleObject.articleContent ?? ""
let nodeID = currentIssueArticleObject.nodeID ?? 0
cellWithoutCoverImage.currentIssueArticlesHeadlineLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
cellWithoutCoverImage.currentIssueArticlesHeadlineLabel.text = title
cellWithoutCoverImage.currentIssueArticlesAuthorLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
cellWithoutCoverImage.currentIssueArticlesAuthorLabel.text = author
cellWithoutCoverImage.currentIssueArticlesPublishDateLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
cellWithoutCoverImage.currentIssueArticlesPublishDateLabel.text = timeStampDateString
return cellWithoutCoverImage
} else {
}
}
else {
}
}
EDIT 1: Revised code - still does not work
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
let row = indexPath.row
switch(row) {
case 0:
let cellWithCoverImage = tableView.dequeueReusableCellWithIdentifier(CurrentIssueFrontCoverTableCellIdentifier, forIndexPath: indexPath) as! CurrentIssueFrontCoverTableViewCell
if let currentIssueFrontCoverObject = currentIssueObjects.objectAtIndex(indexPath.row) as? IssueElement {
let title = currentIssueFrontCoverObject.title ?? ""
let timeStampDateObject = NSDate(timeIntervalSince1970: NSTimeInterval(currentIssueFrontCoverObject.timeStamp))
let timeStampDateString = dateFormatter.stringFromDate(timeStampDateObject)
let issueNumber = currentIssueFrontCoverObject.issueNumber ?? ""
let volumeNumber = currentIssueFrontCoverObject.volumeNumber ?? ""
let nodeID = currentIssueFrontCoverObject.nodeID ?? 0
let imageURL = currentIssueFrontCoverObject.imageURL ?? ""
cellWithCoverImage.request?.cancel()
if let coverImage = self.imageCache.objectForKey(imageURL) as? UIImage {
cellWithCoverImage.currentIssueFrontCoverImageView.image = coverImage
} else {
cellWithCoverImage.currentIssueFrontCoverImageView.image = nil
cellWithCoverImage.request = Alamofire.request(.GET, imageURL).responseImage() { response in
if let coverImage = response.result.value {
self.imageCache.setObject(response.result.value!, forKey: imageURL)
cellWithCoverImage.currentIssueFrontCoverImageView.image = coverImage
} else {
return
}
}
}
} else {
break
}
return cellWithCoverImage;
// Populating data in the "Articles" type cells
default:
let cellWithoutCoverImage = tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as! CurrentIssueArticlesTableViewCell
if let currentIssueArticleObject = currentIssueObjects.objectAtIndex(indexPath.row) as? IssueElement {
let title = currentIssueArticleObject.title ?? ""
let timeStampDateObject = NSDate(timeIntervalSince1970: NSTimeInterval(currentIssueArticleObject.timeStamp))
let timeStampDateString = dateFormatter.stringFromDate(timeStampDateObject)
let author = currentIssueArticleObject.author ?? ""
let issueNumber = currentIssueArticleObject.issueNumber ?? ""
let volumeNumber = currentIssueArticleObject.volumeNumber ?? ""
let articleContent = currentIssueArticleObject.articleContent ?? ""
let nodeID = currentIssueArticleObject.nodeID ?? 0
cellWithoutCoverImage.currentIssueArticlesHeadlineLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
cellWithoutCoverImage.currentIssueArticlesHeadlineLabel.text = title
cellWithoutCoverImage.currentIssueArticlesAuthorLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
cellWithoutCoverImage.currentIssueArticlesAuthorLabel.text = author
cellWithoutCoverImage.currentIssueArticlesPublishDateLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
cellWithoutCoverImage.currentIssueArticlesPublishDateLabel.text = timeStampDateString
return cellWithoutCoverImage;
} else {
break
}
}
}
You need to remove the last else in your code cose it's empty. Also you could use a switch like:
switch(row){
case 0:{
// code with the CurrentIssueFrontCoverTableViewCell
....
return cellWithCoverImage;
}
default:{
// code with the CurrentIssueArticlesTableViewCell
...
return cellWithoutCoverImage;
}
}
The comment from Victor is correct. Because if you were to step through every possible outcome of the function, you could possibly reach the end of it without returning anything. You will need to provide a return statement for every possible outcome, including inside all of the 'else' blocks at the end that are currently empty.
Your problem is this:
} else {
return
}
You can't have empty returns in a method expecting a return type, you need to return something here.
Every code path in your method must end in a return that returns a UITableViewCell. Anything that does not will make the compiler complain.

getting an error like of malloc_error_break

While reloading a tableView the app crashes and I am getting error
malloc:
error for object 0x7f8c7b99be80: pointer being freed was not allocated
set a breakpoint in malloc_error_break to debug
I have set the Symbolic breakpoint for
malloc_error_break
Also try to find memory leakage with "Instruments" but it just showing same error in console but here is no any memory leakage.
How to solve this issue.
(I am using 8.3 SDK and 6.3.1 Xcode)
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var ResultCellIdentifier = "placementID"
var LoadCellIdentifier = "LoadingCell"
var count = self.arrayOfAllData.count as NSInteger
if count == 0 && indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("LoadingCell") as! UITableViewCell
return cell
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier("placementID") as! PlacementsTableViewCell
indexPATH = indexPath
var tweet = self.arrayOfAllData.objectAtIndex(indexPath.row) as! NSDictionary
let created_at = tweet.valueForKey("created_at") as? NSString
var dateArray : NSArray = created_at!.componentsSeparatedByString(" ")
if dateArray.count != 0 {
let month = dateArray.objectAtIndex(1) as! String
let date = dateArray.objectAtIndex(2) as! String
cell.timeLabel.text = String(format: "%# %#", date,month)
}
///////////any url present in tweet text
var entities = NSDictionary()
entities = tweet.valueForKey("entities") as! NSDictionary
var urlsArray = entities.valueForKey("urls") as! NSArray
if urlsArray.count == 0 {
}else {
for item in urlsArray as! [NSDictionary] {
let expanded_url = item.valueForKey("expanded_url") as? String
}
}
///////////
var tweet_id_str = NSString()
var user_id_str = NSString()
var data = NSData()
// var name = NSString()
///////////count of retweets
var retweet_count = tweet.valueForKey("retweet_count") as! NSInteger
var retweeted_status = tweet.valueForKey("retweeted_status") as! NSDictionary
var favorite_count = retweeted_status.valueForKey("favorite_count") as! NSInteger
///////////tweet id
tweet_id_str = retweeted_status.valueForKey("id_str") as! NSString
if retweeted_status.isEqual(nil) {
}
else {
var user = retweeted_status.valueForKey("user") as! NSDictionary
///////////last update
let created_at = retweeted_status.valueForKey("created_at") as! NSString
///////////
///////////user name who added this tweet
cell.titleLabel.text = user.valueForKey("name") as? String
///////////user id who added this tweet
user_id_str = user.valueForKey("id_str") as! NSString
///////////screen name
let screen_name = user.valueForKey("screen_name") as! NSString
var followers_count = user.valueForKey("followers_count") as! NSInteger
///////////profile image of the tweet
cell.avatarImageView.image = UIImage(named: "Twitter Avatar.jpg")
let profile_image_url = user.valueForKey("profile_image_url") as! NSString
var imageUrl = NSURL(string: profile_image_url as String)
let request: NSURLRequest = NSURLRequest(URL: imageUrl!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
if data != nil {
var image = UIImage(data: data)
cell.avatarImageView.image = image
}
}
})
if retweet_count >= 5 || favorite_count >= 15 || followers_count >= 30000 {
cell.featuredImageView.hidden = false
cell.featuredImageView.image = UIImage(named: "new feature star")
}
else {
cell.featuredImageView.hidden = true
}
}
cell.mailLabel.text = ""
let tweetText = tweet.valueForKey("text") as? NSString
cell.beattypeLabel.text = tweetText as? String
if tweetText?.containsString("#gmail") == true{
NSLog("Mail id is present at index : %d", indexPath.row)
var words = NSArray()
words = NSArray(array: tweetText!.componentsSeparatedByString(" "))
var mailAddress = NSString()
for var i = 0; i < words.count; i++ {
var mailAdd = words.objectAtIndex(i) as! NSString
if mailAdd.rangeOfString("#gmail").location != NSNotFound {
NSLog("mail Address : %#", mailAdd)
if mailAdd.rangeOfString(".com").location == NSNotFound {
var lastChar = mailAdd.characterAtIndex(mailAdd.length-1)
var lastCharStr:NSString = NSString(format: "%ch", lastChar)
mailAddress = mailAdd.stringByAppendingString(".com")
}
}
}
}
return cell
}
}
at the same time Thread 1 showing this
http://i.stack.imgur.com/2YoQp.jpg
(please go through this image)
use
var cell = tableView.dequeueReusableCellWithIdentifier("placementID") as! PlacementsTableViewCell
if cell.isEqual(nil) {
cell = PlacementsTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "placementID")
}
instead of
let cell = tableView.dequeueReusableCellWithIdentifier("placementID") as! PlacementsTableViewCell
and change downloading image in other thread like follow
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
println("This is run on the background queue")
var imageData = NSData(contentsOfURL: imageUrl!)
var image = UIImage(data: imageData!)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
println("This is run on the main queue, after the previous code in outer block")
cell.avatarImageView.image = image
})
})

Resources