iPhone和Apple Watch无法取消存档对方的文件

时间:2019-02-18 11:45:12

标签: ios swift apple-watch nskeyedarchiver watchconnectivity

iPhone和Apple Watch都在相同的NSObject中这样归档文件:

do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: currentRoute!, requiringSecureCoding: false)
            try data.write(to: URL(fileURLWithPath: path!))
            print("save success")
        } catch {
            print("Couldn't write file")
        }

Apple Watch使用self.session?.transferFile(URL(fileURLWithPath: filePath!), metadata: ["name": fileName])将文件发送到iPhone,并且确实收到了文件,但是它不能像在Apple Watch中那样存档。

    func session(_ session: WCSession, didReceive file: WCSessionFile) {


        let name:String = file.metadata!["name"] as! String
        // document directory
        let path = FileHelper.filePathWithName(name: name, isCache: false)

        if FileManager.default.fileExists(atPath: path!){
            do {
                try FileManager.default.removeItem(at: URL(fileURLWithPath: path!))
            }catch{
                print("cannot remove file")
            }
        }
        do{
                try FileManager.default.copyItem(at: file.fileURL, to: URL(fileURLWithPath: path!))
        }catch{
            print("cannot copy file")
        }


        let route = NSKeyedUnarchiver.unarchiveObject(withFile: path!) as? Route
        print(route) // it's nil

    }

我还尝试将相同格式的文件从iPhone文档目录手动复制到Apple Watch,Apple Watch也无法取消存档。但是他们可以打开自己创建的文件。

NSKeyedArchiver是否已指定拒绝其他应用程序打开的符号?


我认为问题可能是Route类中的NSCoding,该类已存档,Apple Watch和iPhone均使用它:

class Route: NSObject, NSCoding, CLLocationManagerDelegate {

    public func encode(with aCoder: NSCoder) {
        aCoder.encode(startTime, forKey: "startTime")
        aCoder.encode(endTime, forKey: "endTime")
        aCoder.encode(locations, forKey: "locations")
    }

    let distanceFilter: CLLocationDistance = 10

    var startTime: NSDate
    var endTime: NSDate
    var locations: Array<CLLocation>

    override init() {

        startTime = NSDate()
        endTime = startTime
        locations = Array()
    }

    deinit {
//        println("deinit")
    }

    /// NSCoding

    required init?(coder aDecoder: NSCoder) {
        startTime = aDecoder.decodeObject(forKey: "startTime") as! NSDate
        endTime = aDecoder.decodeObject(forKey: "endTime") as! NSDate
        locations = aDecoder.decodeObject(forKey: "locations") as! Array
    }

//.........

}

0 个答案:

没有答案