如何在Userdefaults中获取列表值

时间:2017-08-03 03:01:24

标签: swift3 nsuserdefaults

我在一个func中有json的数据1获取数据有1个列表值但我用userdefault输出func调用值我得到1个值。

func getdevices() {
    var token = UserDefaults.standard.string(forKey: "token")
    print("token", token)
    var username = UserDefaults.standard.string(forKey: "username")
    print("username", username)
    let url: URL = URL(string: "/public/devices")!
    let request: NSMutableURLRequest = NSMutableURLRequest(url: url)

    request.httpMethod = "Get"
    request.setValue(token , forHTTPHeaderField: "token")
    request.setValue(username, forHTTPHeaderField: "username")

    var responseError: NSError?
    var response: URLResponse?

    var urlData: Data?

    do {

        urlData = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response)

    } catch let error as NSError {
        responseError = error
        urlData = nil
    }
    if ( urlData != nil ) {
        let res = response as! HTTPURLResponse!;

        print("Response code: %ld tra ve" , res?.statusCode);

        if ((res?.statusCode)! >= 200 && (res?.statusCode)! < 300)
        {
            //let responseData:NSString  = NSString(data:urlData!, encoding:String.Encoding.utf8.rawValue)!
            if let json = try? JSONSerialization.jsonObject(with: urlData!, options: []) as? [String : Any],
                //let dataArray = json?["status"] as? [String : Any],

                let items = json?["units"] as? [[String : Any]] {

                for item in items {

                    var lat = item["latitude"] as? String
                    UserDefaults.standard.set(lat, forKey: "latitude")
                    var test = UserDefaults.standard.double(forKey: "latitude")

                    print("test", test)

                    var long = item["longitude"] as? String
                    UserDefaults.standard.set(long, forKey: "longitude")

                    print("long", long)
                    var devid = item["devid"] as? String
                    UserDefaults.standard.set(devid, forKey: "devid")
                    var devname = item["devname"] as? String
                    UserDefaults.standard.set(devname, forKey: "devname")

                    var speed = item["speed"] as? String
                    UserDefaults.standard.set(speed, forKey: "speed")

                    var statustt = item["status"] as? String
                    UserDefaults.standard.set(statustt, forKey: "statusxe")
                    var drivername = item["drivername"] as? String
                    UserDefaults.standard.set(drivername, forKey: "drivername")
                    var address = item["address"] as? String
                    UserDefaults.standard.set(address, forKey: "address")

                    print("address", address)
                }
            }
        }
    }
}

但是,当应用程序存在func它没有获取列表数据时,它有一个值。

override func viewDidAppear(_ animated: Bool) {

    GMSServices.provideAPIKey("AIzaSyB2IJzNc2s5km1qvdwAePDEat1OdPsOFVA")

    guard let address = UserDefaults.standard.string(forKey: "address") else {return}
getdevices()

    var lat = UserDefaults.standard.double(forKey: "latitude")
    var long = UserDefaults.standard.double(forKey: "longitude")
    var devname = UserDefaults.standard.string(forKey: "devname")
    var speed = UserDefaults.standard.string(forKey: "speed")
    print("lat", lat)
    print("long", long)
    print("address***", address)



    let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: long, zoom: 10)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    view = mapView
    let marKer = GMSMarker()
    marKer.position = CLLocationCoordinate2D(latitude: lat, longitude: long)
    marKer.icon = UIImage(named: "vehicle_105")
    marKer.title = "Biển số \(devname)"
    //marKer.title = "Speed \(speed)"
    marKer.map = mapView

}

1 个答案:

答案 0 :(得分:0)

您只能在UserDefaults的单个密钥下存储单个对象/值。问题是,您在循环的每次迭代中覆盖相同键下的值。你应该做的是在循环之前创建一个数组,在循环中将值添加到该数组中,并在循环完成迭代后将数组存储在UserDefaults中。

if let items = json?["units"] as? [[String : Any]] {
    var latitudes = [String]()
    var longitudes = [String]() 
    var devids = [String]()
    var devnames = [String]()       
    var speeds = [String]()
    var statustts = [String]()
    var drivernames = [String]()
    var addresses = [String]()

    for item in items {
        let lat = item["latitude"] as? String
        latitudes.append(lat)            

        let long = item["longitude"] as? String
        longitudes.append(long)

        let devid = item["devid"] as? String
        devids.append(devid)

        var devname = item["devname"] as? String
        devnames.append(lat)

        var speed = item["speed"] as? String
        speeds.append(speed)

        var statustt = item["status"] as? String
        statuses.append(statustt)

        var drivername = item["drivername"] as? String
        drivernames.append(drivername)

        var address = item["address"] as? String
        addresses.append(address)
    }

    UserDefaults.standard.set(latitudes, forKey: "latitude")
    UserDefaults.standard.set(longitudes, forKey: "longitude")
    UserDefaults.standard.set(devids, forKey: "devid")
    UserDefaults.standard.set(devnames, forKey: "devname")
    UserDefaults.standard.set(speeds, forKey: "speed")
    UserDefaults.standard.set(statustts, forKey: "statusxe")
    UserDefaults.standard.set(drivername, forKey: "drivername")
    UserDefaults.standard.set(addresses, forKey: "address")
}