Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/113.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 文件存在于iCloud中,但query.resultCount=0_Ios_Swift_Icloud - Fatal编程技术网

Ios 文件存在于iCloud中,但query.resultCount=0

Ios 文件存在于iCloud中,但query.resultCount=0,ios,swift,icloud,Ios,Swift,Icloud,应用程序使用iCloud存储符合可编码协议的对象 在重新安装应用程序或在新设备上安装应用程序的情况下,我尝试使用NSMetadataQuery从iCloud的现有文件中获取数据,但query.resultCount=0 我认为我的问题在于如何正确设置NSMetadataQuery谓词 请就这个问题给我提意见 class ViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak

应用程序使用iCloud存储符合可编码协议的对象

在重新安装应用程序或在新设备上安装应用程序的情况下,我尝试使用NSMetadataQuery从iCloud的现有文件中获取数据,但query.resultCount=0

我认为我的问题在于如何正确设置NSMetadataQuery谓词

请就这个问题给我提意见

class ViewController: UIViewController {

@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var weightLabel: UILabel!

@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var weightTextField: UITextField!

let fileManager = FileManager.default

var iCloudContainer: URL? {
    return FileManager().url(forUbiquityContainerIdentifier: nil)
}

func getFilePath(container: URL, fileName: String) -> String {
    let filePath = container.appendingPathComponent(fileName).path

    return filePath
}

lazy var metadataQuery : NSMetadataQuery = {
    let query = NSMetadataQuery()

    query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
    var pred = NSPredicate(format: "NOT %K.pathExtension = '.'", NSMetadataItemFSNameKey)
    query.predicate = pred

    return query
}()

override func viewDidLoad() {
    super.viewDidLoad()

    self.metadataQuery.start()

    NotificationCenter.default.addObserver(self, selector: #selector(refreshFileList), name: NSNotification.Name.NSMetadataQueryDidUpdate, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(refreshFileList), name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: nil)
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

@objc func refreshFileList() {
    print(metadataQuery.resultCount)
    metadataQuery.enumerateResults { (item: Any, index: Int, stop: UnsafeMutablePointer<ObjCBool>) in
        let metadataItem = item as! NSMetadataItem

        if isMetadataItemDownloaded(item: metadataItem) == false {

            let url = metadataItem.value(forAttribute: NSMetadataItemURLKey) as! URL

            try? FileManager.default.startDownloadingUbiquitousItem(at: url)
        }
    }

    let container = self.iCloudContainer
    let filePath = getFilePath(container: container!, fileName: "Person")

    if let jsonData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? Data {
        if let person = try? JSONDecoder().decode(Person.self, from: jsonData) {
            nameLabel.text = person.name
            weightLabel.text = String(person.weight)
        } else {
            nameLabel.text = "NOT decoded"
            weightLabel.text = "NOT decoded"
        }
    } else {
        nameLabel.text = "NOT unarchived"
        weightLabel.text = "NOT unarchived"
    }
}

func isMetadataItemDownloaded(item : NSMetadataItem) -> Bool {
    if item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String == NSMetadataUbiquitousItemDownloadingStatusCurrent {
        return true
    } else {
        return false
    }
}

@IBAction func saveButtonPressed(_ sender: UIButton) {
    let container = self.iCloudContainer
    let filePathe = getFilePath(container: container!, fileName: "Person")

    let person = Person(name: nameTextField.text!, weight: Double(weightTextField.text!)!)
    let jsonData = try? JSONEncoder().encode(person)
    NSKeyedArchiver.archiveRootObject(jsonData!, toFile: filePathe)
}
类ViewController:UIViewController{
@IBVAR名称标签:UILabel!
@IBOutlet弱var权重标签:UILabel!
@IBMOutlet弱变量nameTextField:UITextField!
@IBOutlet弱var权重文本字段:UITextField!
让fileManager=fileManager.default
var-iCloudContainer:URL{
返回FileManager().url(用于泛素容器标识符:nil)
}
func getFilePath(容器:URL,文件名:String)->String{
让filePath=container.appendingPathComponent(fileName.path)
返回文件路径
}
惰性变量metadataQuery:NSMetadataQuery={
let query=NSMetadataQuery()
query.searchScopes=[NSMetadataQueryUbiquitousDocumentsScope]
var pred=NSPredicate(格式:“不是%K.pathExtension=”。”,NSMetadataItemFSNameKey)
query.predicate=pred
返回查询
}()
重写func viewDidLoad(){
super.viewDidLoad()
self.metadataQuery.start()
NotificationCenter.default.addObserver(self,选择器:#选择器(refreshFileList),名称:NSNotification.name.nsMetadataQueryIDUpdate,对象:nil)
NotificationCenter.default.addObserver(self,选择器:#选择器(refreshFileList),名称:NSNotification.name.nsMetadataQueryDifinishGathering,对象:nil)
}
脱硝{
NotificationCenter.default.removeObserver(自)
}
@objc func刷新文件列表(){
打印(metadataQuery.resultCount)
metadataQuery.enumerateResults{(项:Any,索引:Int,停止:UnsafemeutablePointer)位于
将metadataItem=项设为!NSMetadataItem
如果isMetadataItemDownloaded(项:metadataItem)=false{
将url=metadataItem.value(for属性:NSMetadataItemURLKey)设为!url
try?FileManager.default.startDownloadingUbiquitousItem(位于:url)
}
}
let container=self.iCloudContainer
让filePath=getFilePath(容器:container!,文件名:“Person”)
如果让jsonData=NSKeyedUnarchiver.unarchiveObject(带文件:filePath)作为?数据{
如果让person=try?JSONDecoder().decode(person.self,from:jsonData){
namelab.text=person.name
weightLabel.text=字符串(person.weight)
}否则{
namelab.text=“未解码”
weightlab.text=“未解码”
}
}否则{
namelab.text=“未归档”
weightlab.text=“未归档”
}
}
func isMetadataItemDownloaded(项目:NSMetadataItem)->Bool{
如果item.value(对于属性:NSMetadataUbiquitousItemDownloadingStatusKey)为?字符串==NSMetadataUbiquitousItemDownloadingStatusCurrent{
返回真值
}否则{
返回错误
}
}
@iAction func SaveButton已按下(\发送方:UIButton){
let container=self.iCloudContainer
让filepath=getFilePath(容器:container!,文件名:“Person”)
让person=person(名称:nameTextField.text!,权重:Double(weightTextField.text!))
让jsonData=try?JSONEncoder().encode(个人)
归档对象(jsonData!,toFile:filePathe)
}

}首先谓词的格式应该是

 query.predicate = NSPredicate(format: "%K == %@", NSMetadataItemFSNameKey, "Person")
第二,在容器中显示保存文件,如下所示

let filePath = container.appendingPathComponent("Documents").appendingPathComponent(fileName).path
文件路径必须为/Documents/file

没有文档目录,查询无法找到文件