【问题标题】:Having trouble retrieving data from CloudKit从 CloudKit 检索数据时遇到问题
【发布时间】:2016-08-14 18:27:12
【问题描述】:

我无法从 cloudkit 获取位置。该位置已上传,但是当我尝试将它们打印出来并加载时,它们不会被下载。我没有收到任何错误。

此函数将位置上传到 CloudKit:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {
        let location = locations.last
        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.015, longitudeDelta: 0.015))
        self.mapView.setRegion(region, animated: true)
        self.locationManager.stopUpdatingLocation()//
        let locationRecord = CKRecord(recordType: "location")
        locationRecord.setObject(location, forKey: "location")
        let publicData = CKContainer.defaultContainer().publicCloudDatabase
        publicData.saveRecord(locationRecord) { record, error in
        }
            if error == nil
            {
                print("Location saved")
            }
        event1 = locations
    }

此函数从 CloudKit 获取位置:

func loadLocation()
     {
        let locations = [CKRecord]()
        let publicData1 = CKContainer.defaultContainer().publicCloudDatabase
        let query1 = CKQuery(recordType: "location", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray:nil))
        publicData1.performQuery(query1, inZoneWithID: nil) { (results: [CKRecord]?, error: NSError?) -> Void in
            if let locations = results
            {
                self.locations = locations
                print(locations)
            }
        }
     }

【问题讨论】:

  • 你能详细说明问题到底是什么吗?它是从CKRecords 创建CLLocationCoordinate2D 吗?它是否在地图上显示图钉?
  • 现在我无法创建 CLLocationCoordinate2D。我也不认为这些位置正在被获取。 @grimfrog
  • 保存代码中括号错误。但是你必须知道,因为你所拥有的不会编译对吗?

标签: ios swift cloudkit cllocation ckrecord


【解决方案1】:

为此,我做了一个单元测试,通过了:

//
//  CloudKitLocationsTests.swift
//

import XCTest
import UIKit
import CoreLocation
import CloudKit

class CloudKitLocationsTests: XCTestCase {

    let locations = [ CLLocation(latitude: 34.4, longitude: -118.33), CLLocation(latitude: 32.2, longitude: -121.33) ]

    func storeLocationToCloud(location:CLLocation) {
        let locationRecord = CKRecord(recordType: "location")
        locationRecord.setObject(location, forKey: "location")
        let publicData = CKContainer.defaultContainer().publicCloudDatabase
        publicData.saveRecord(locationRecord) { (records, error) in
            if error != nil {
                print("error saving locations: \(error)")
            } else {
                print("Locations saved: \(records)")
            }
        }
    }

    func fetchLocationsFromCloud(completion: (error:NSError?, records:[CKRecord]?) -> Void) {
        let query = CKQuery(recordType: "Location", predicate: NSPredicate(value: true))
        CKContainer.defaultContainer().publicCloudDatabase.performQuery(query, inZoneWithID: nil){
            (records, error) in
            if error != nil {
                print("error fetching locations")
                completion(error: error, records: nil)
            } else {
                print("found locations: \(records)")
                completion(error: nil, records: records)
            }
        }
    }

    func testSavingLocations(){

        let testExpectation = expectationWithDescription("saveLocations")
        var n = 0
        for location in self.locations {
            let locationRecord = CKRecord(recordType: "Location")
            locationRecord["location"] = location
            let publicData = CKContainer.defaultContainer().publicCloudDatabase
            publicData.saveRecord(locationRecord) { (records, error) in
                if error != nil {
                    print("error saving locations: \(error)")
                } else {
                    print("Locations saved: \(records)")
                }
                n += 1
                if n >= self.locations.count {
                    testExpectation.fulfill()
                }
            }
        }

        // do something then call fulfill (in callback)

        waitForExpectationsWithTimeout(10){ error in
            if error != nil {
                XCTFail("timed out waiting on expectation: \(testExpectation)")
            }
        }

    }

    func testFetchingLocations(){
        let testExpectation = expectationWithDescription("FetchLocations")

        fetchLocationsFromCloud(){ (error, records) in
            if error != nil {
                XCTFail("error fetching locations")
            } else {
                XCTAssertGreaterThan(records!.count, 0)
            }
            // do something then call fulfill (in callback)
            testExpectation.fulfill()
        }

        waitForExpectationsWithTimeout(10){ error in
            if error != nil {
                XCTFail("timed out waiting on expectation: \(testExpectation)")
            }
        }

    }


}

请注意,您的位置/位置大小写不匹配。另外,我正在做一个下标来设置字段值。

运行它就可以了。从位置管理器回调中获取位置与 CloudKit 无关,因此您应该可以根据需要将其插入。

另一件事:我确实打开了允许您在 ID 字段上查询位置记录类型的选项。

【讨论】:

  • 我正在尝试调用 fetchFromThe Cloud 函数:loadLocation((error, self.locArray)) 并收到错误消息:“无法转换类型的值 '(NSError?, [CKRecord]?) ' (aka '(Optional, Optional>)') 到预期的参数类型 '(error: NSError?, records: [CKRecord]?) -> Void'" @Rob
  • 显示代码。听起来您没有正确执行尾随关闭。查看测试调用该方法的方式:它不提供完成作为参数,但在调用后有一个闭包。 @Caleb
【解决方案2】:

如果您的问题是检索CLLocation 的数组,试试这个:

publicData1.performQuery(query1, inZoneWithID: nil) { records, error in
    var locations = [CLLocation]()
    if let records = records {
        for record in records {
            if let location = record["location"] as? CLLocation {
                locations.append(location)
            }
        }
    }
}

【讨论】:

  • 我在 "locations.append(location)" 行之后添加了一个 print("h") 并且它没有被打印,所以我不确定它是否在函数中走得那么远
  • "for" 行是打印第一次停止工作时
猜你喜欢
  • 1970-01-01
  • 2019-12-24
  • 2016-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多