首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何以CKAsset的形式正确地将图像发送到CKAsset?

如何以CKAsset的形式正确地将图像发送到CKAsset?
EN

Stack Overflow用户
提问于 2016-05-01 16:59:27
回答 3查看 5.5K关注 0票数 10

我有一个映像(UIImage,它也是url ),我试图将它作为一个CKAsset发送到CloudKit,但是我有一个错误:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Non-file URL'。以下是代码:

代码语言:javascript
复制
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)
        }
    })
}

我有URL,我可以打印它,复制并粘贴到我的导航器,它将显示我的图像!所以我不知道这里发生了什么..。

如果我使用的是UIImage而不是它的URL,那会更容易吗?因为,就像我以前说的,我有他们两个!任何帮助都是非常感谢的!谢谢,伙计们!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-05-01 18:33:11

根据我的经验,将上传UIImage保存为CKAsset的唯一方法是:

  1. 将映像暂时保存到磁盘
  2. 创建CKAsset
  3. 删除临时文件
代码语言:javascript
复制
let data = UIImagePNGRepresentation(myImage); // UIImage -> NSData, see also UIImageJPEGRepresentation
let url = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(NSUUID().UUIDString+".dat")
do {
    try data!.writeToURL(url, options: [])
} catch let e as NSError {
    print("Error! \(e)");
    return
}
newUser["photo"] = CKAsset(fileURL: url)

// ...

publicData.saveRecord(newUser, completionHandler: { (record: CKRecord?, error: NSError?) in
    // Delete the temporary file
    do { try NSFileManager.defaultManager().removeItemAtURL(url) }
    catch let e { print("Error deleting temp file: \(e)") }

    // ...
}

几个月前,我提交了一份错误报告,要求能够从内存中的CKAsset中初始化NSData,但还没有完成。

票数 14
EN

Stack Overflow用户

发布于 2016-08-13 16:53:17

我做了一些稍微不同的事情:我创建了一个类,您可以在多个地方使用,而且由于Swift具有可运行的去初始化功能(与C++不同),它可以自己清理:

代码语言:javascript
复制
//
//  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)")
            }
        }
    }
    
    
}

下面是一个单元测试(假设在测试目标中有一个名为秒表的图像):

代码语言:javascript
复制
//
//  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)")
    }


}

最初是作为UIImage上的一个扩展来做的,但后来deinit让我转到了一个类。

票数 3
EN

Stack Overflow用户

发布于 2017-05-30 21:28:27

这是如何将图像保存到Cloudkit的目标C版本

这需要相当多的挖掘,因为没有太多的信息可以进行,但这是可行的。

代码语言:javascript
复制
  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);
                              }


                          }];



                 }




            }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36969341

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档