iCloud之Using Asset and Location Fields

来源:互联网 发布:vc新建c语言项目 编辑:程序博客网 时间:2024/05/01 21:08

Using Asset and Location Fields

使用资产和位置字段

CloudKit专为存储大量数据文件提供字段类型,并通过位置获取记录。使用这些数据类型来利用性能改进CloudKit提供此数据类型的。您还可以通过位置获取记录。例如,在一个用户定义的区域的地图显示记录。

Store Large Files in CloudKit

您可以使用资产字段类型存储大型数据文件CloudKit。资产由相关记录所有,CloudKit处理您回收的垃圾。 CloudKit也有效地上传和下载资产。


在代码中,资产字段类型由一个CKAsset对象表示。此代码片段艺术品记录到一个资源文件设置了一个资产领域。

  // Create a URL to the local file
   NSURL *resourceURL = [NSURL fileURLWithPath:@"…"];
   if (resourceURL){
      CKAsset *asset = [[CKAsset alloc] initWithFileURL:resourceURL];
      artworkRecord[@"image"] = asset;
   }
如果在保存记录,文件上传到iCloud。


节省一个记录类型与资产领域的类似的代码添加到您的应用程序并运行它。要保存记录,读 Save Records.

Verify Your Steps

要验证您的架构变更内容和记录被保存到iCloud,读 View Record Types by Using CloudKit DashboardView Records Using CloudKit Dashboard。当你与一个资产对象查看记录,CloudKit仪表板显示的二进制数据的大小。任选地,下载或从记录中删除的二进制数据。

../Art/6_asset_attribte_2x.png

Add Location Fields

如果您的记录都有一个地址或其他位置的数据,可以将其保存在记录一个CLLocation对象,后来被定位提取记录。例如,你的应用程序可能会显示引脚代表在地图上的记录。


此代码段使用CLGeocoder类将字符串转换地址到一个位置对象,并将其存储在记录中。

CLGeocoder *geocoder = [CLGeocoder new];
[geocoder geocodeAddressString:artwork[kArtworkAddressKey] completionHandler:^(NSArray *placemark, NSError *error){
   if (!error) {
      if (placemark.count > 0){
         CLPlacemark *placement = placemark[0];
         artworkRecord[kArtworkLocationKey] = placement.location;
      }
   }
   else {
      // insert error handling here
   }
   // Save the record to the database
}];
保存一个记录类型与位置字段类似的代码添加到您的应用程序并运行它。要保存记录,读 Save Records。

Verify Your Steps

当您在CloudKit仪表板视图中的记录,它显示位置字段的经度和纬度。

../Art/6_location_attribte_2x.png

Fetch Records by Location

一旦你有位置,数据库中的数据,您可以获取使用包含一个记录类型,谓词和排序描述符的查询按位置记录。在谓语中指定的位置字段必须被索引为获取成功。


这段代码获取其位置是在10万米旧金山的所有记录。

// Get the public database object
CKDatabase *publicDatabase = [[CKContainer defaultContainer] publicCloudDatabase];
 
// Create a predicate to retrieve records within a radius of the user's location
CLLocation *fixedLocation = [[CLLocation alloc] initWithLatitude:37.7749300 longitude:-122.4194200];
CGFloat radius = 100000; // meters
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"distanceToLocation:fromLocation:(location, %@) < %f", fixedLocation, radius];
 
// Create a query using the predicate
CKQuery *query = [[CKQuery alloc] initWithRecordType:@"Artwork" predicate:predicate];
 
// Execute the query
[publicDatabase performQuery:query inZoneWithID:nil completionHandler:^(NSArray *results, NSError *error) {
   if (error) {
      // Error handling for failed fetch from public database
   }
   else {
      // Display the fetched records
   }
}];
在此iOS应用,固定位置的指定半径内的艺术作品被取出。

../Art/6_fetching_by_location_2x.png

要了解更多关于位置和地图,阅读 Location and Maps Programming Guide.


概括


在本章中,您学习了如何:


通过添加CKAsset场记录,并保存记录添加一个资产类型以一个记录类型
添加的地区,达到创纪录的类型使用CLLocation对象
通过获取位置对象




































0 0
原创粉丝点击