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?
Related
I get this crash error:
MXNet2CoreML[11383:1168377]
*** Terminating app due to uncaught exception 'NSRangeException', reason:
*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
*** First throw call stack: (0x18333f164 0x182588528 0x18329a020 0x1007894bc 0x1011ef94c 0x1011b0420 0x1021412cc 0x10214128c
0x102145ea0 0x1832e7344 0x1832e4f20 0x183204c58 0x1850b0f84
0x18c95d5c4 0x1007d8894 0x182d2456c)
libc++abi.dylib: terminating with uncaught exception of type
NSException
Here is the Complete Code
//Owais: - Map setup
func resetRegion(){
let region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, 5000, 5000)
mapKit.setRegion(region, animated: true)
}
var myLatitude = ""
var myLongitude = ""
// Array of annotations
let annotation = MKPointAnnotation()
var places = PredictionLocationList().place
var locationsArray = [String]()
var ie: Int = 0
#IBOutlet var mapKit: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let defaults = UserDefaults.standard
let data = defaults.data(forKey: "selectedimage")
let uiimage2 = UIImage(data: data!)
defaults.synchronize()
let image = uiimage2
// imageView.image = image
predictUsingVision(image: image!)
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeDown.direction = UISwipeGestureRecognizerDirection.down
self.view.addGestureRecognizer(swipeDown)
// Do any additional setup after loading the view.
}
#objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
print("Swiped right")
case UISwipeGestureRecognizerDirection.down:
print("Swiped down")
self.dismiss(animated: true, completion: nil)
case UISwipeGestureRecognizerDirection.left:
print("Swiped left")
case UISwipeGestureRecognizerDirection.up:
print("Swiped up")
default:
break
}
}
}
func predictUsingVision(image: UIImage) {
guard let visionModel = try? VNCoreMLModel(for: model.model) else {
fatalError("Something went wrong")
}
let request = VNCoreMLRequest(model: visionModel) { request, error in
if let observations = request.results as? [VNClassificationObservation] {
let top3 = observations.prefix(through: 2)
.map { ($0.identifier, Double($0.confidence)) }
self.show(results: top3)
}
}
request.imageCropAndScaleOption = .centerCrop
let handler = VNImageRequestHandler(cgImage: image.cgImage!)
try? handler.perform([request])
}
typealias Prediction = (String, Double)
func show(results: [Prediction]) {
var s: [String] = []
for (i, pred) in results.enumerated() {
let latLongArr = pred.0.components(separatedBy: "\t")
print("lat long \(latLongArr)")
myLatitude = latLongArr[1]
myLongitude = latLongArr[2]
ie = i
s.append(String(format: "%d: %# %# (%.2f%%)", i + 1, myLatitude, myLongitude, pred.1 * 100))
LocationByCoordinates(latitude: myLatitude, longitude: myLongitude)
// let ew1 = (String(format: "%.2f%", pred.1 * 100))
// print(ew1)
// let double1 = Double(ew1)
// self.doubles.append(double1!)
// print("eueue \(self.doubles)")
// let maxDouble = max(max(double1, double2), double3)
print("first latidue \(myLatitude),,,, \(myLongitude)")
places[i].title = String(i+1)
places[i].coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(myLatitude)!, longitude: CLLocationDegrees(myLongitude)!)
}
// predictionLabel.text = s.joined(separator: "\n")
// Map reset
resetRegion()
mapKit.centerCoordinate = places[0].coordinate
// Show annotations for the predictions on the map
mapKit.addAnnotations(places)
// Zoom map to fit all annotations
zoomMapFitAnnotations()
}
func zoomMapFitAnnotations() {
var zoomRect = MKMapRectNull
for annotation in mapKit.annotations {
let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0)
if (MKMapRectIsNull(zoomRect)) {
zoomRect = pointRect
} else {
zoomRect = MKMapRectUnion(zoomRect, pointRect)
}
}
self.mapKit.setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(50, 50, 50, 50), animated: true)
}
func LocationByCoordinates (latitude: String,longitude:String) {
let mapsKey = UserDefaults.standard.string(forKey: "maps_key") ?? ""
Alamofire.request("https://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)&key=\(mapsKey)").responseJSON { response in
if let json = response.result.value {
let request = json as? NSDictionary
if let id = request!["results"] {
// print(id)
let ide = id as? NSArray
let formatted_address = ide![0]
let fors = formatted_address as! NSDictionary
//print(fors.value(forKey: "formatted_address"))
let forss = fors.value(forKey: "formatted_address")
self.locationsArray.append(forss as? String ?? "")
if self.ie == 0 {
self.places[0].identifier = (forss as? String)!
} else if self.ie == 1 {
self.places[1].identifier = (forss as? String)!
} else if self.ie == 2 {
self.places[2].identifier = (forss as? String)!
}
}
}
}
}
}
extension Collection where Indices.Iterator.Element == Index {
subscript (safe index: Index) -> Iterator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
The problem is in this line let formatted_address = ide![0]
If an array is empty, you can't get it's first element with [0] because there is no element at all!
All you have to do is check if the array is not empty before unwrapping it:
if ide!.count > 0 {
//Your code
}
To avoid force-unwrapping ide, you may want to use optional binding like so:
if let id = request!["results"], let ide = id as? NSArray {
let formatted_address = ide[0]
let fors = formatted_address as! NSDictionary
//rest of your code
}
In my project concept i need a insert 10k data when user open the application. I integrate core data for storing data but its take 1 to 5 minutes.
Here is my code ?
func inserChatMessage(_ message: String, chatId: String, onCompletion completionHandler:((_ message: ChatMessage) -> Void)?) {
var objMessage: ChatMessage? = nil
if let obj = ChatMessage.createEntity() {
objMessage = obj
}
objMessage?.messageId = ""
objMessage?.message = message
objMessage?.chatId = chatId
objMessage?.senderId = AIUser.current.userId
objMessage?.createAt = Date()
objMessage?.updateAt = Date()
let cManager = CoreDataManager.sharedManager
cManager.saveContext()
if let completionHandler = completionHandler, let objMessage = objMessage {
completionHandler(objMessage)
}
}
Coredata is not a threadsafe. And as per your requirement you need to save large amount of data on app launch. So If you will save those data using main thread, your app will get hanged. So Instead on saving large amount of data on main thread you can save those data on background thread. Coredata is supporting multi threading concept by providing parent child context concept.
I have done same in one of my project and its working fine. Here i have attached code.
func savePersonalMessagesOnBackGroundThread(arrMessages:NSArray,responseData:#escaping () -> Void)
{
print(arrMessages)
let temporaryChatContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
temporaryChatContext.parent = self.managedObjectContext
temporaryChatContext.perform({() -> Void in
for i in 0..<arrMessages.count
{
let msgDic = arrMessages[i] as! NSDictionary
_ = self.saveMessageInLocalDB(dictMessage: msgDic, managedObjectContext: temporaryChatContext, onBackground: true)
if i == arrMessages.count - 1 {
do {
try temporaryChatContext.save()
runOnMainThreadWithoutDeadlock {
DLog(message: "Thred \(Thread.isMainThread)")
if(self.managedObjectContext.hasChanges)
{
self.saveContext()
responseData()
}
}
}
catch {
print(error)
}
}
}
})
}
func saveMessageInLocalDB(dictMessage:NSDictionary, managedObjectContext:NSManagedObjectContext,onBackground:Bool) -> Chat
{
var chatObj : Chat! = Chat()
var receiveId: Int32!
var flag:Bool = false
print(dictMessage)
// let predicate = NSPredicate(format:"uniqueId == %# and senderId = %d and receiverId = %d","\(dictMessage.value(forKey:keyuniqueId)!)",Int32(dictMessage.value(forKey:keysenderId) as! Int64),Int32(dictMessage.value(forKey:keyreceiverId) as! Int64))
let predicate = NSPredicate(format:"uniqueId == %#","\(dictMessage.value(forKey:keyuniqueId)!)")
let objContext = managedObjectContext
let fetchRequest = NSFetchRequest<Chat>(entityName: ENTITY_CHAT)
let disentity: NSEntityDescription = NSEntityDescription.entity(forEntityName: ENTITY_CHAT, in: objContext)!
fetchRequest.predicate = predicate
fetchRequest.entity = disentity
do{
let results = try managedObjectContext.fetch(fetchRequest as! NSFetchRequest<NSFetchRequestResult>) as! [Chat]
if(results.count > 0)
{
chatObj = results[0]
chatObj.messageId = Int32(dictMessage.value(forKey:keymessageId) as! Int64)
chatObj.dateOnly = dictMessage.value(forKey:keydateOnly) as! String?
}
else{
//receiveId = Int32(dictMessage.value(forKey:keyreceiverId) as! Int64)
//self.createNewChatObject(dictMessage: dictMessage, receiverId: receiveId, managedObjectContext: managedObjectContext)
chatObj = NSEntityDescription.insertNewObject(forEntityName:ENTITY_CHAT,into: managedObjectContext) as? Chat
if dictMessage[keymessageId] != nil {
chatObj.messageId = dictMessage.value(forKey:keymessageId) as! Int32
}
if(chatObj.message?.length != 0)
{
chatObj.message = dictMessage.value(forKey:keychatMessage) as? String
}
chatObj.messageType = Int32(dictMessage.value(forKey:keymessageType) as! Int64)
chatObj.senderId = Int32(dictMessage.value(forKey:keysenderId) as! Int64)
if(chatObj.senderId != Int32((APP_DELEGATE.loggedInUser?.id!)!))
{
let contactObj = self.getContactByContactId(contactId: Int32(dictMessage.value(forKey:keysenderId) as! Int64))
if(contactObj == nil)
{
_ = self.saveUnknownUserASContact(msgDict: dictMessage as! Dictionary<String, Any>)
}
}
chatObj.receiverId = Int32(dictMessage.value(forKey:keyreceiverId) as! Int64)
chatObj.uniqueId = dictMessage.value(forKey:keyuniqueId) as? String
chatObj.mediaName = dictMessage.value(forKey:keymediaName) as? String
print(NSDate())
if dictMessage[keycreatedDate] != nil {
let utcDate : NSDate = DateFormater.getUTCDateFromUTCString(givenDate: dictMessage.value(forKey:keycreatedDate) as! String)
chatObj.createdDate = utcDate
chatObj.updatedDate = utcDate
}
else
{
chatObj.createdDate = NSDate()
chatObj.updatedDate = NSDate()
}
if(chatObj.senderId == Int32((APP_DELEGATE.loggedInUser?.id)!))
{
chatObj.chatUser = chatObj.receiverId
}
else
{
chatObj.chatUser = chatObj.senderId
}
if dictMessage[keystatus] != nil {
chatObj.status = Bool((dictMessage.value(forKey:keystatus) as! Int64) as NSNumber)
}
switch Int(chatObj.messageType)
{
case MSG_TYPE.MSG_Text.rawValue:
chatObj.cellType = (chatObj.senderId != Int32((APP_DELEGATE.loggedInUser?.id!)!) ? Int32(CELL_TYPE.CELL_TEXT_RECEIVER.rawValue) : Int32(CELL_TYPE.CELL_TEXT_SENDER.rawValue))
case MSG_TYPE.MSG_Image.rawValue:
chatObj.cellType = (chatObj.senderId != Int32((APP_DELEGATE.loggedInUser?.id!)!) ? Int32(CELL_TYPE.CELL_IMAGE_RECEIVER.rawValue) : Int32(CELL_TYPE.CELL_IMAGE_SENDER.rawValue))
self.saveMedia(chatObj: chatObj)
default :
// chatObj.cellType = Int32(CELL_TYPE.CELL_LOAD_MORE.rawValue)
break
}
}
// deviceMake = 1;
if(!onBackground)
{
self.saveContext()
}
}
catch
{
}
return chatObj
}
Using the basic example below I can insert 10k records very quickly. The main thing that has changed here compared to your code is that I loop through and create the entities and then call save() at the very end. So you are performing one write call to the db instead of 10k. You are writing more information in that one call but it is still much quicker.
import UIKit
import CoreData
class ViewController: UIViewController {
lazy var sharedContext: NSManagedObjectContext? = {
return (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
}()
override func viewDidLoad() {
super.viewDidLoad()
if let messages = getMessages(), messages.count > 0 {
printMessages(messages: messages)
} else {
loadChatMessages()
printMessages(messages: getMessages())
}
}
private func printMessages(messages: [Message]?) {
guard let messages = messages else { return }
for message in messages {
print(message.message)
}
}
private func getMessages() -> [Message]? {
let request = NSFetchRequest<Message>(entityName: "Message")
let messages = try? self.sharedContext?.fetch(request)
return messages ?? nil
}
private func loadChatMessages() {
var counter = 1
while counter <= 10000 {
let message = Message(entity: Message.entity(), insertInto: self.sharedContext)
message.message = "This is message number \(counter)"
message.read = false
message.timestamp = Date()
counter = counter + 1
}
do {
try self.sharedContext?.save()
} catch {
print(error)
}
}
}
As mentioned in my comment above, you can improve this further by doing it in the background (see Twinkle's answer for an example of how to switch to a background thread), you can also provide a pre-filled (pre-seeded) core data database that already contains the 10k records with your app. so it doesn't need to load this on initial load.
To do this you would fill the db locally on your dev machine and then copy it to the project bundle. On initial load you can check to see if your db filename exists in the documents folder or not. If it doesn't copy it over from the bundle and then use that DB for core data.
The problem is described in title, but to be more specific here is a full picture.
I have a custom table view cell subclass with label inside it displaying the countdown timer. When there a small portion of timers it works fine, but with a lot of data I need to display timers far beyond the visible cells and when I scroll down fast and then scroll up fast, the timer values in cells start to show different values until a certain point in time, after which it shows the right value.
I tried different variants for those reuseable cells, but I can’t spot a problem. Help needed!!!
Here is the code of implementation of logic.
Custom cell subclass:
let calendar = Calendar.current
var timer: Timer?
var deadlineDate: Date? {
didSet {
updateTimeLabel()
}
}
override func awakeFromNib() {
purchaseCellCardView.layer.cornerRadius = 10
let selectedView = UIView(frame: CGRect.zero)
selectedView.backgroundColor = UIColor.clear
selectedBackgroundView = selectedView
}
override func prepareForReuse() {
super.prepareForReuse()
if timer != nil {
print("Invalidated!")
timer?.invalidate()
timer = nil
}
}
func configure(for purchase: Purchase) {
purchaseSubjectLabel.text = purchase.subject
startingPriceLabel.text = purchase.NMC
stageLabel.text = purchase.stage
fzImageView.image = purchase.fedLaw.contains("44") ? #imageLiteral(resourceName: "FZ44") : #imageLiteral(resourceName: "FZ223")
timeLabel.isHidden = purchase.stage == "Работа комиссии"
warningImageView.image = purchase.warningImage
}
func updateTimeLabel() {
setTimeLeft()
timer = Timer(timeInterval: 1, repeats: true) { [weak self] _ in
guard let strongSelf = self else {return}
strongSelf.setTimeLeft()
}
RunLoop.current.add(timer!, forMode: .commonModes)
}
#objc private func setTimeLeft() {
let currentDate = getCurrentLocalDate()
if deadlineDate?.compare(currentDate) == .orderedDescending {
var components = calendar.dateComponents([.day, .hour, .minute, .second], from: currentDate, to: deadlineDate!)
let dayText = (components.day! == 0 || components.day! < 0) ? "" : String(format: "%i", components.day!)
let hourText = (components.hour == 0 || components.hour! < 0) ? "" : String(format: "%i", components.hour!)
switch (dayText, hourText) {
case ("", ""):
timeLabel.text = String(format: "%02i", components.minute!) + ":" + String(format: "%02i", components.second!)
case ("", _):
timeLabel.text = hourText + " ч."
default:
timeLabel.text = dayText + " дн."
}
} else {
stageLabel.text = "Работа комиссии"
timeLabel.text = ""
timeLabel.isHidden = true
timer?.invalidate()
}
}
private func getCurrentLocalDate() -> Date {
var now = Date()
var nowComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now)
nowComponents.timeZone = TimeZone(abbreviation: "UTC")
now = calendar.date(from: nowComponents)!
return now
}
deinit {
print("DESTROYED")
timer?.invalidate()
timer = nil
}
The most important part of tableView(_cellForRowAt:)
case .results:
if filteredArrayOfPurchases.isEmpty {
let cell = tableView.dequeueReusableCell(
withIdentifier: TableViewCellIdentifiers.nothingFoundCell,
for: indexPath)
let label = cell.viewWithTag(110) as! UILabel
switch segmentedControl.index {
case 1:
label.text = "Нет закупок способом\n«Запрос предложений»"
case 2:
label.text = "Нет закупок способом\n«Конкурс»"
case 3:
label.text = "Нет закупок способом\n«Аукцион»"
default:
label.text = "Нет закупок способом\n«Запрос котировок»"
}
return cell
} else {
let cell = tableView.dequeueReusableCell(
withIdentifier: TableViewCellIdentifiers.purchaseCell,
for: indexPath) as! PurchaseCell
cell.containerViewTopConstraint.constant = indexPath.row == 0 ? 8.0 : 4.0
cell.containerViewBottomConstraint.constant = indexPath.row == filteredArrayOfPurchases.count - 1 ? 8.0 : 4.0
let purchase = filteredArrayOfPurchases[indexPath.row]
cell.configure(for: purchase)
if cell.timer != nil {
cell.updateTimeLabel()
} else {
search.getDeadlineDateAndTimeToApply(purchase.purchaseURL, purchase.fedLaw, purchase.stage, completion: { (date) in
cell.deadlineDate = date
})
}
return cell
}
And the last piece of a puzzle:
func getDeadlineDateAndTimeToApply(_ url: URL?, _ fedLaw: String, _ stage: String, completion: #escaping (Date) -> ()) {
var deadlineDateAndTimeToApply = Date()
guard stage != "Работа комиссии" else { return }
if let url = url {
dataTask = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if let error = error as NSError?, error.code == -403 {
// TODO: Add alert here
return
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let data = data, let html = String(data: data, encoding: .utf8), let purchasePageBody = try? SwiftSoup.parse(html), let purchaseCard = try? purchasePageBody.select("td").array() else {return}
let mappedArray = purchaseCard.map(){String(describing: $0)}
if fedLaw.contains("44") {
guard let deadlineDateToApplyString = try? purchaseCard[(mappedArray.index(of: "<td class=\"fontBoldTextTd\">Дата и время окончания подачи заявок</td>"))! + 1].text().components(separatedBy: " ") else {return}
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
let deadlineDateToApply = deadlineDateToApplyString.first!
let deadlineTimeToApply = deadlineDateToApplyString[1]
guard let deadlineDateAndTimeToApplyCandidate = dateFormatter.date(from: "\(deadlineDateToApply) \(deadlineTimeToApply)") else {return}
deadlineDateAndTimeToApply = deadlineDateAndTimeToApplyCandidate
} else {
guard let deadlineDateToApplyString = try? purchaseCard[(mappedArray.index(of: "<td>Дата и время окончания подачи заявок<br> (по местному времени заказчика)</td>"))! + 1].text().components(separatedBy: " ") else {return}
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
let deadlineDateToApply = deadlineDateToApplyString.first!
let deadlineTimeToApply = deadlineDateToApplyString[2]
guard let deadlineDateAndTimeToApplyCandidate = dateFormatter.date(from: "\(deadlineDateToApply) \(deadlineTimeToApply)") else {return}
deadlineDateAndTimeToApply = deadlineDateAndTimeToApplyCandidate
}
DispatchQueue.main.async {
completion(deadlineDateAndTimeToApply)
}
})
dataTask?.resume()
}
}
A few notes:
Tried resetting deadlineDate to nil in prepareForReuse() - doesn’t help;
Using SwiftSoup Framework to parse HTML as you can see in the last code example if it matters.
This is quite a lot of code but from what you are describing your issue is in reusing cells.
You would do well to separate the timers out of the cells and put them inside your objects. It is where they belong (or in some manager like view controller). Imagine having something like the following:
class MyObject {
var timeLeft: TimeInterval = 0.0 {
didSet {
if timeLeft > 0.0 && timer == nil {
timer = Timer.scheduled...
} else if timeLeft <= 0.0, let timer = timer {
timer.invalidate()
self.timer = nil
}
delegate?.myObject(self, updatedTimeLeft: timeLeft)
}
}
weak var delegate: MyObjectDelegate?
private var timer: Timer?
}
Now all you need is is a cell for row at index path to assign your object: cell.myObject = myObjects[indexPath.row].
And your cell would do something like:
var myObject: MyObject? {
didSet {
if oldValue.delegate == self {
oldValue.delegate = nil // detach from previous item
}
myObject.delegate = self
refreshUI()
}
}
func myObject(_ sender: MyObject, updatedTimeLeft timeLeft: TimeInterval) {
refreshUI()
}
I believe the rest should be pretty much straight forward...
Your problem is here:
search.getDeadlineDateAndTimeToApply(purchase.purchaseURL,
purchase.fedLaw,
purchase.stage,
completion: { (date) in
cell.deadlineDate = date
})
getDeadlineDateAndTimeToApply runs asynchronously, calculates something, and then updates the cell.deadlineData in the main thread (which is fine). But in the meantime, while calculating something, the user might have scrolled up and down, the cell might have been reused for another row, and now the update updates the cell incorrectly.
What you need to do is: Do not store the UITableViewCell directly. Instead, keep track of the IndexPath to be updated, and once the caluclation is done, retrieve the the cell that belongs to that IndexPath and update this.
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.
I'm pretty new to swift, so please try to bear with me.
I'm currently able to download CKRecords and insert them into an array, "birdFacts". Each record includes a few strings, an image (CKAsset), a date, and an int. When they initially download from iCloud, everything works fine.
Everything is saving as expected, except the image. When I reload the data, the asset doesn't show up.
Here is my code to load saved data:
if let savedFacts = loadFacts() {
birdFacts = savedFacts
print("successfully loaded saved bird facts")
}
func loadFacts() -> [CKRecord]? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(BirdFact.ArchiveURL.path!) as? [CKRecord]
}
This is my code to save the array:
func saveFacts() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(birdFacts, toFile: BirdFact.ArchiveURL.path!)
if !isSuccessfulSave {
print("Failed to save bird facts")
}
}
This is within my custom class definition file:
import UIKit
import CloudKit
class BirdFact: NSObject, NSCoding {
//MARK: PROPERTIES
var birdName: String
var photo: CKAsset
var birdFact: String
var date: NSDate
var sortingDate: Int
//MARK: TYPES
struct PropertyKey {
static let namekey = "name"
static let photokey = "photo"
static let factkey = "fact"
static let datekey = "date"
static let sortingDatekey = "sortingDate"
}
//MARK: INITIALIZATION
init?(birdName: String, photo: CKAsset, birdFact: String, date: NSDate, sortingDate: Int){
//init stored props
self.birdName = birdName
self.photo = photo
self.birdFact = birdFact
self.date = date
self.sortingDate = sortingDate
super.init()
if birdName.isEmpty || birdFact.isEmpty {
return nil
}
}
//MARK: NSCODING
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(birdName, forKey: PropertyKey.namekey)
aCoder.encodeObject(photo, forKey: PropertyKey.photokey)
aCoder.encodeObject(birdFact, forKey: PropertyKey.factkey)
aCoder.encodeObject(date, forKey: PropertyKey.datekey)
aCoder.encodeObject(sortingDate, forKey: PropertyKey.sortingDatekey)
}
required convenience init?(coder aDecoder: NSCoder) {
let birdName = aDecoder.decodeObjectForKey(PropertyKey.namekey) as! String
let photo = aDecoder.decodeObjectForKey(PropertyKey.photokey) as! CKAsset
let birdFact = aDecoder.decodeObjectForKey(PropertyKey.factkey) as! String
let date = aDecoder.decodeObjectForKey(PropertyKey.datekey) as! NSDate
let sortingDate = aDecoder.decodeObjectForKey(PropertyKey.sortingDatekey) as! Int
self.init(birdName: birdName, photo: photo, birdFact: birdFact, date: date, sortingDate: sortingDate)
}
//MARK: ARCHIVING PATHS
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("BirdFacts")
}
I'm saving whenever I finish downloading and sorting the records. Any idea what is going wrong?
EDIT: Included CloudKit query. I should note that I never save anything to iCloud, only download existing records.
func allprevFacts(date: String, olddate: Int){
act.startAnimating()
let container = CKContainer.defaultContainer()
let publicDB = container.publicCloudDatabase
//let factPredicate = NSPredicate(format: "recordID = %#", CKRecordID(recordName: date))
let factPredicate = NSPredicate(format: "date <= %#", NSDate())
let query = CKQuery(recordType: "BirdFacts", predicate: factPredicate)
publicDB.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in
if error != nil {
print(error)
}
else {
dispatch_async(dispatch_get_main_queue()){
//print(results)
var count = 0
var sortedresults = [Int]()
for result in results! {
var b = result.valueForKey("sortingDate") as! Int
sortedresults.append(b)
}
print(sortedresults)
while count < sortedresults.count {
if sortedresults[count] <= olddate {
sortedresults.removeAtIndex(count)
}
else {
count = count + 1
}
}
print(sortedresults)
while sortedresults.count > 0 {
var d: Int = 0
let a = sortedresults.maxElement()
print(a)
while d < sortedresults.count{
if sortedresults[d] == a {
sortedresults.removeAtIndex(d)
self.birdFacts.append(results![d])
self.tableFacts.reloadData()
self.tableFacts.hidden = false
}
d = d + 1
print(d)
}
}
self.saveFacts()
print("saving bird facts")
self.tableFacts.hidden = false
}
}
}
act.stopAnimating()