2016-11-30 13 views
1

Здравствуйте, в моем текущем проекте у меня есть:Как сэкономить [GMSPolyline], так что, когда пользователь закрывает и открывает приложение все еще сохраняет данные

class SecondController: UIViewController, CLLocationManagerDelegate { 

var allPoly : [GMSPolyline] = [] 
private let rootKey = "rootKey" 

func applicationWillResignActive(notification: NSNotification) 
    { 
     let filePath = self.dataFilePath() 
     let savedPolys = SavedPolys() 
     let array = self.allPoly as NSArray 
     savedPolys.alPoly = array as? [GMSPolyline] 
     let data = NSMutableData() 
     let archiver = NSKeyedArchiver(forWritingWith: data) 
     archiver.encode(savedPolys, forKey: rootKey) 
     archiver.finishEncoding() 
     data.write(toFile: filePath, atomically: true) 
    } 

    func dataFilePath() -> String 
    { 
     let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) 
     let documentsDirectory = paths[0] as NSString 
     return documentsDirectory.appendingPathComponent("data.archive") as String 
    } 

    func buttonPressed() 
    { 
     //adds a polyline to allPoly! 
    } 

    } 

а также еще один класс:

import Foundation 
import GoogleMaps 

class SavedPolys: NSObject, NSCoding, NSCopying 
{ 
    var alPoly: [GMSPolyline]? 
    let polyKey = "polyKey" 

    override init() 
    { 

    } 

    required init?(coder aDecoder: NSCoder) 
    { 
     alPoly = aDecoder.decodeObject(forKey: polyKey) as? [GMSPolyline] 
    } 

    func encode(with aCoder: NSCoder) { 
     if let savePoly = alPoly 
     { 
      aCoder.encode(savePoly, forKey: polyKey) 
     } 
    } 

    func copy(with zone: NSZone? = nil) -> Any { 
     let copy = SavedPolys() 
     if let polysToCopy = alPoly 
     { 
      var newPolys = Array<GMSPolyline>() 
      for poly in polysToCopy 
      { 
       newPolys.append(poly) 
      } 
      copy.alPoly = newPolys 
     } 
     return copy 
    } 
} 

Я пытаюсь сделать так, если пользователь добавит полисы в массив allPoly, а затем закроет их приложение, массив будет сохранен, а затем перезагружен при открытии приложения. Я попытался следовать главе из учебника моего класса (откуда все это происходит), но этот текущий код дает мне ошибку в этой строке: «archiver.encode (savedPolys, forKey: rootKey)». В нем говорится, что «непризнанный селектор отправлен в экземпляр». Может кто-нибудь мне помочь? Есть ли более простой способ? Благодаря!

+0

вы имеете в виду, используя UserDefaults.standard материал? – skyleguy

+0

Почему вы задаете вопрос как комментарий на свой собственный пост? :) –

+1

там был комментарий, на который я отвечал, но его не было D: lol Я понимаю, что это выглядит смешно сейчас – skyleguy

ответ

0

Код, который вы копируете, немного устарел, и были внесены изменения в API, поэтому он бросает ошибки. Вот измененный код:

Swift 2,3

class SavedPolys : NSObject, NSCoding, NSCopying 
{ 
    var alPoly: [GMSPolyline]? 
    let polyKey = "polyKey" 

    override init() 
    { 

    } 

    required init?(coder aDecoder: NSCoder) 
    { 
    alPoly = aDecoder.decodeObjectForKey(polyKey) as? [GMSPolyline] 
    } 

    func encodeWithCoder(aCoder: NSCoder) 
    { 
    if let savePoly = alPoly 
    { 
     aCoder.encodeObject(savePoly, forKey: polyKey) 
    } 
    } 

    func copyWithZone(zone: NSZone) -> AnyObject 
    { 
    let copy = SavedPolys() 
    if let polysToCopy = alPoly 
    { 
     var newPolys = Array<GMSPolyline>() 
     for poly in polysToCopy 
     { 
     newPolys.append(poly) 
     } 
     copy.alPoly = newPolys 
    } 
    return copy 
    } 
} 


@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 

    var allPoly : [GMSPolyline] = [] 
    private let rootKey = "rootKey" 

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    // Override point for customization after application launch. 

    let filePath = self.dataFilePath() 
    let savedPolys = SavedPolys() 
    let array = self.allPoly as NSArray 
    savedPolys.alPoly = array as? [GMSPolyline] 
    let data = NSMutableData() 
    let archiver = NSKeyedArchiver(forWritingWithMutableData: data) 
    archiver.encodeObject(savedPolys, forKey: rootKey) 
    archiver.finishEncoding() 
    data.writeToURL(NSURL(fileURLWithPath: filePath), atomically: true) 


    return true 
    } 

    func dataFilePath() -> String 
    { 
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 
    let documentsDirectory = paths[0] as NSString 
    return documentsDirectory.stringByAppendingPathComponent("data.archive") 
    } 
} 

Swift 3,0

class SavedPolys : NSObject, NSCoding, NSCopying 
{ 
    var alPoly: [GMSPolyline]? 
    let polyKey = "polyKey" 

    override init() 
    { 

    } 

    required init?(coder aDecoder: NSCoder) 
    { 
    alPoly = aDecoder.decodeObject(forKey: polyKey) as? [GMSPolyline] 
    } 

    func encode(with aCoder: NSCoder) 
    { 
    if let savePoly = alPoly 
    { 
     aCoder.encode(savePoly, forKey: polyKey) 
    } 
    } 

    func copy(with zone: NSZone? = nil) -> Any 
    { 
    let copy = SavedPolys() 
    if let polysToCopy = alPoly 
    { 
     var newPolys = Array<GMSPolyline>() 
     for poly in polysToCopy 
     { 
     newPolys.append(poly) 
     } 
     copy.alPoly = newPolys 
    } 
    return copy 
    } 
} 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 
    var allPoly : [GMSPolyline] = [] 
    private let rootKey = "rootKey" 

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
    // Override point for customization after application launch. 
    let filePath = self.dataFilePath() 
    let savedPolys = SavedPolys() 
    let array = self.allPoly as NSArray 
    savedPolys.alPoly = array as? [GMSPolyline] 
    let data = NSMutableData() 
    let archiver = NSKeyedArchiver(forWritingWith: data) 
    archiver.encode(savedPolys, forKey: rootKey) 
    archiver.finishEncoding() 
    data.write(to: NSURL(fileURLWithPath: filePath) as URL, atomically: true) 

    return true 
    } 

    func dataFilePath() -> String 
    { 
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) 
    let documentsDirectory = paths[0] as NSString 
    return documentsDirectory.appendingPathComponent("data.archive") 
    } 
} 
+0

Я вижу, что вы говорите, что это совместимо с Swift 2.3, но я использую Swift 3.0, как вы думаете, он все равно будет работать? – skyleguy

+0

Я также добавил код Swift 3.0. –

+0

hmmm. Я забыл упомянуть, что мои основные уже подклассы UIViewController, и поэтому он не даст мне подкласс из UIResponder из-за ошибки «множественного наследования»! Есть идеи? – skyleguy