Search code examples
iosswiftswift4icloud-drive

NSMetadataQuery isUpdating breaks after Reachability changes to none Swift 4


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


Solution

  • 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?