2016-11-13 96 views
2

我有一個iOS應用程序,其中有2種方式,用戶可以得到一個畫面:如何從UIImage獲取URL?

  1. 從照片庫中選擇它(UIImagePickerController

  2. 從定製的相機點擊它

這裏是我的代碼點擊自定義相機的圖像(這是在一個名爲Camera,這是一個UIView的子類的自定義類)

func clickPicture(completion:@escaping (UIImage) -> Void) { 

    guard let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) else { return } 

    videoConnection.videoOrientation = .portrait 
    stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) -> Void in 

     guard let buffer = sampleBuffer else { return } 

     let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) 
     let dataProvider = CGDataProvider(data: imageData! as CFData) 
     let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent) 

     let image = UIImage(cgImage: cgImageRef!, scale: 1, orientation: .right) 

     completion(image) 


    }) 
} 

這裏是我點擊ViewController內的圖像:

@IBAction func clickImage(_ sender: AnyObject) { 
    cameraView.clickPicture { (image) in 
     //use "image" variable 
    } 
} 

後來,我嘗試上傳使用CloudKit此圖片到用戶的iCloud帳戶。但是,我收到一條錯誤消息,稱該記錄太大。然後我遇到了this SO post,它說使用CKAsset。但是,CKAsset的唯一構造函數需要URL

有沒有一種通用的方法,我可以從任何UIImage得到URL?否則,如何從我使用自定義相機單擊的圖像(我看到其他posts關於從UIImagePickerController獲取網址)中獲得URL?謝謝!

+0

我怎麼會創建一個臨時位置網址? – penatheboss

回答

1

CKAsset代表一些外部文件(圖像,視頻,二進制數據等)。這就是爲什麼它需要URL作爲初始參數。

在你的情況我會建議使用以下步驟以大圖片上傳到CloudKit:

  1. 保存UIImage到本地存儲(例如,文檔目錄)。
  2. 初始化CKAsset帶本地存儲器中映像的路徑。
  3. 將資產上傳到雲。
  4. 上傳完成後從本地存儲中刪除圖像。

下面是一些代碼:

// Save image. 
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! 
let filePath = "\(path)/MyImageName.jpg" 

UIImageJPEGRepresentation(image, 1)!.writeToFile(filePath, atomically: true) 

let asset = CKAsset(fileURL: NSURL(fileURLWithPath: filePath)!) 
// Upload asset here. 

// Delete image. 
do { 
    try FileManager.default.removeItem(atPath: filePath) 
} catch { 
    print(error) 
} 
+0

感謝您的回覆!但是,在將記錄保存到CloudKit時,我正在獲取以下錯誤:「沒有這樣的文件或目錄」。什麼可能導致這個? – penatheboss