Ios 如何将映像作为CKAsset正确发送到CloudKit?
我有一个图像(UIImage和它的url),我试图将其作为CKAsset发送到CloudKit,但我遇到了以下错误:Ios 如何将映像作为CKAsset正确发送到CloudKit?,ios,cloudkit,Ios,Cloudkit,我有一个图像(UIImage和它的url),我试图将其作为CKAsset发送到CloudKit,但我遇到了以下错误:由于未捕获的异常“NSInvalidArgumentException”终止应用程序,原因是:“非文件url”。代码如下: override func viewDidLoad() { super.viewDidLoad() send2Cloud() } func send2Cloud() { let newUser = CKRec
由于未捕获的异常“NSInvalidArgumentException”终止应用程序,原因是:“非文件url”
。代码如下:
override func viewDidLoad() {
super.viewDidLoad()
send2Cloud()
}
func send2Cloud() {
let newUser = CKRecord(recordType: "User")
let url = NSURL(string: self.photoURL)
let asset = CKAsset(fileURL: url!)
newUser["name"] = self.name
newUser["photo"] = asset
let publicData = CKContainer.defaultContainer().publicCloudDatabase
publicData.saveRecord(newUser, completionHandler: { (record: CKRecord?, error: NSError?) in
if error == nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
print("User saved")
})
} else {
print(error?.localizedDescription)
}
})
}
我有网址,我可以打印它,复制和粘贴到我的导航器,它会显示我的图像!所以,我不知道这里发生了什么
如果我使用UIImage而不是它的URL,会更容易吗?因为,正如我之前说过的,我两个都有!非常感谢您的帮助!谢谢,伙计们 根据我的经验,将上传
UIImage
保存为CKAsset
的唯一方法是:
几个月前,我提交了一份错误报告,请求能够从内存中初始化
CKAsset
,但还没有完成。我做了一件稍有不同的事情:我创建了一个可以在多个地方使用的类,这要感谢Swift的去初始化功能(与C++不同),它会自行清理:
//
// ImageAsset.swift
//
import CloudKit
import UIKit
class ImageAsset {
let image:UIImage
var url:NSURL?
var asset:CKAsset? {
get {
let data = UIImagePNGRepresentation(self.image)
self.url = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(NSUUID().UUIDString+".dat")
if let url = self.url {
do {
try data!.writeToURL(url, options: [])
} catch let e as NSError {
print("Error! \(e)")
}
return CKAsset(fileURL: url)
}
return nil
}
}
init(image:UIImage){
self.image = image
}
deinit {
if let url = self.url {
do {
try NSFileManager.defaultManager().removeItemAtURL(url) }
catch let e {
print("Error deleting temp file: \(e)")
}
}
}
}
下面是一个单元测试,用于测试它(假设测试目标中有一个名为stopwatch的图像):
本来打算在UIImage上做一个扩展,但后来Denit让我转到了一个类。这是如何将图像保存到Cloudkit的Objective C版本 这需要相当多的挖掘,因为没有太多的信息,但这是可行的
if([results count] <= 0) {
NSLog(@"this Record doesnt exist so add it ok!! %@", error);
CKRecordID *wellKnownID = [[CKRecordID alloc]
initWithRecordName:idString];
CKRecord *entitiesName = [[CKRecord alloc] initWithRecordType:@"mySavedDetails"
recordID:wellKnownID];
[entitiesName setObject:idString
forKey:@"myDetailsId"];
[entitiesName setObject:self.myName.text
forKey:@"myName"];
if (myUIImage.image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
@"test.png" ];
NSData* data = UIImagePNGRepresentation(myUIImage.image.image);
[data writeToFile:path atomically:YES];
//so we get the full path of the uiimage
NSLog(@"Path details %@",path);
NSURL* myImagePath = nil;
myImagePath =
[[NSBundle mainBundle] URLForResource:path
withExtension:@"png"];
//here we change the path of Image which is a string to a URL
NSURL *yourURL = [NSURL fileURLWithPath:path];
CKAsset* myImageAsset = nil;
myImageAsset =
[[CKAsset alloc] initWithFileURL:yourURL];
[entitiesName setObject: myImageAsset
forKey:@"myImage"];
[publicDatabase saveRecord: entitiesName
completionHandler:^(CKRecord *savedState, NSError *error) {
if (error) {
NSLog(@"ERROR SAVING: %@", error);
}
}];
}
}
if([results count]读取错误。self.photoURL
不是文件URL。它是什么?打印URL并在问题中发布输出。self.photoURL
是一个字符串。我使用Facebook请求获取用户数据!这是输出:()如果字符串表示本地文件路径,则只需使用fileURLWithPath
初始值设定项而不是string
初始值设定项来正确创建NSURL
。谢谢,圣诞老人!!如果要将CKAsset对象转换为数据对象,或将CKAsset对象转换为图像,您会怎么做呢ode>类型“Data”的值没有成员“writeToURL”
您应该将文件写入临时目录,而不是documentsDirectory
//
// ImageExtensionTests.swift
//
import CloudKit
import XCTest
@testable import BudgetImpactEstimator
class ImageExtensionTests: XCTestCase {
let testImageName = "stopwatch" // provide the name of an image in test bundle
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testConvertingImageToAsset() {
guard let image = UIImage(named: self.testImageName) else {
XCTFail("failed to load image")
return
}
let imageAsset = ImageAsset(image: image)
XCTAssertNotNil(imageAsset)
guard let asset = imageAsset.asset else {
XCTFail("failed to get asset from image")
return
}
print("constructed asset: \(asset)")
}
}
if([results count] <= 0) {
NSLog(@"this Record doesnt exist so add it ok!! %@", error);
CKRecordID *wellKnownID = [[CKRecordID alloc]
initWithRecordName:idString];
CKRecord *entitiesName = [[CKRecord alloc] initWithRecordType:@"mySavedDetails"
recordID:wellKnownID];
[entitiesName setObject:idString
forKey:@"myDetailsId"];
[entitiesName setObject:self.myName.text
forKey:@"myName"];
if (myUIImage.image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
@"test.png" ];
NSData* data = UIImagePNGRepresentation(myUIImage.image.image);
[data writeToFile:path atomically:YES];
//so we get the full path of the uiimage
NSLog(@"Path details %@",path);
NSURL* myImagePath = nil;
myImagePath =
[[NSBundle mainBundle] URLForResource:path
withExtension:@"png"];
//here we change the path of Image which is a string to a URL
NSURL *yourURL = [NSURL fileURLWithPath:path];
CKAsset* myImageAsset = nil;
myImageAsset =
[[CKAsset alloc] initWithFileURL:yourURL];
[entitiesName setObject: myImageAsset
forKey:@"myImage"];
[publicDatabase saveRecord: entitiesName
completionHandler:^(CKRecord *savedState, NSError *error) {
if (error) {
NSLog(@"ERROR SAVING: %@", error);
}
}];
}
}