2017-03-25 6 views
-1

私は、ユーザが録画したビデオのサムネイル画像をコレクションビューに設定しようとしています。映像が記録され、選択されると、この関数は、ディレクトリにサムネイル画像を保存するには、この機能を使用して...ドキュメントディレクトリへのビデオ...StringファイルのパスからUIImageを使用する

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 

    let mediaType = info[UIImagePickerControllerMediaType] as! NSString 
    dismiss(animated: true, completion: nil) 

    if mediaType == kUTTypeMovie { 
     // Componenets for a unique ID for the video 
     var uniqueVideoID = "" 
     var videoURL:NSURL? = NSURL() 
     var uniqueID = "" 
     uniqueID = NSUUID().uuidString 

     // Get the path as URL 
     videoURL = info[UIImagePickerControllerMediaURL] as? URL as NSURL? 
     let myVideoVarData = try! Data(contentsOf: videoURL! as URL) 

     // Write the video to the Document Directory at myVideoVarData (and set the video's unique ID) 
     let docPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) 
     let documentsDirectory: AnyObject = docPaths[0] as AnyObject 
     uniqueVideoID = uniqueID + "VIDEO.MOV" 
     let docDataPath = documentsDirectory.appendingPathComponent(uniqueVideoID) as String 
     try? myVideoVarData.write(to: URL(fileURLWithPath: docDataPath), options: []) 
     print("docDataPath under picker ", docDataPath) 
     print("Video saved to documents directory") 

     // Create a thumbnail image from the video (first frame) 
     let asset = AVAsset(url: URL(fileURLWithPath: docDataPath)) 
     let assetImageGenerate = AVAssetImageGenerator(asset: asset) 
     assetImageGenerate.appliesPreferredTrackTransform = true 
     let time = CMTimeMake(asset.duration.value/3, asset.duration.timescale) 
     if let videoImage = try? assetImageGenerate.copyCGImage(at: time, actualTime: nil) { 
      // Add thumbnail to documents directory 
      let thumbnailPath = saveImageToDocumentDirectory(UIImage(cgImage: videoImage)) 
      // Add thumbnail & video path to Post object 
      let video = Post(pathToVideo: URL(fileURLWithPath: docDataPath), thumbnail: thumbnailPath) 
      posts.append(video) 
      print("Video saved to Post object") 
     } 
    } 
} 

を保存します。今すぐ

func saveImageToDocumentDirectory(_ chosenImage: UIImage) -> String { 
    let directoryPath = NSHomeDirectory().appending("/Documents/") 
    if !FileManager.default.fileExists(atPath: directoryPath) { 
     do { 
      try FileManager.default.createDirectory(at: NSURL.fileURL(withPath: directoryPath), withIntermediateDirectories: true, attributes: nil) 
     } catch { 
      print(error) 
     } 
    } 
    let filename = NSDate().string(withDateFormatter: yyyytoss).appending(".jpg") 
    let filepath = directoryPath.appending(filename) 
    let url = NSURL.fileURL(withPath: filepath) 
    do { 
     try UIImageJPEGRepresentation(chosenImage, 1.0)?.write(to: url, options: .atomic) 
     return String.init("/Documents/\(filename)") 

    } catch { 
     print(error) 
     print("file cant not be save at path \(filepath), with error : \(error)"); 
     return filepath 
    } 
} 

問題は、UIImageセルのコレクションビューを保存したサムネイルで表示したいということです。上記のようにサムネイルがStringとして保存されるPostオブジェクトがあります。それはコレクションビューで細胞画像を設定することになるとだから、私はここにUIImageとしての私のオブジェクト(UIImageへの文字列のファイルパス)からサムネイルを使用するかどうかはわかりません。

cell.postImage.image = posts[indexPath.row].thumbnail 

は誰をいこれを可能にする方法を知っていますか?

EDIT:画像を保存し、ファイルパスを取得するための更新機能:

func saveImageToDocumentDirectory(_ chosenImage: UIImage) -> URL { 
    let fm = FileManager.default 

    // Get date/time 
    let dateFormatter = DateFormatter() 
    dateFormatter.dateFormat = "ddhhmmss" 
    let now = dateFormatter.string(from: NSDate() as Date) 

    // Make the filename (String) 
    let filename = now.appending(".jpg") 
    let docsurl = try? fm.url(for:.documentDirectory, in: .userDomainMask, 
          appropriateFor: nil, create: false) 
    // Make the filepath 
    let filepath = docsurl?.appendingPathComponent(filename) 

    // Save filename to documents directory 
    do { 
     try UIImageJPEGRepresentation(chosenImage, 1.0)?.write(to: docsurl!, options: .atomic) 

    } catch { 
     print(error) 
     print("file cant not be save at path \(filepath), with error : \(error)"); 

     // Return the filepath 
     return filepath! 
    } 
} 

とタイプURLであるとPostオブジェクトにthumbnailを変更しました。このような追加のポストオブジェクト:すべての

let thumbnailPath = saveImageToDocumentDirectory(UIImage(cgImage: videoImage)) 

let video = Post(pathToVideo: URL(fileURLWithPath: docDataPath), thumbnail: URL(fileURLWithPath: thumbnailPath)) 

答えて

1

まず、NS接頭辞なしスウィフトでNSDateNSDataNSURLなど3.
のみを使用した構造体を使用しないでください。

ファイルパスを持っているので、ファイルからイメージを作成し、postImage

let filePath = posts[indexPath.row].thumbnail 
cell.postImage.image = UIImage(contentsOfFile:filePath) 

ノートに割り当てる:NSHomeDirectory().appending("/Documents/")がまったく動作しません。 didFinishPickingMediaWithInfoメソッドのようにドキュメントディレクトリを取得する必要があります。

+0

問題は、彼がファイルパスを持っていないことです。彼は '/ Documents/\(filename)' 'を格納していますが、これはまったく間違っています。 – matt

+0

私は@mattを知っているので、私はノートを追加しました – vadian

+0

おかげでvadian 'UIImage(contentsOfFile ...')は私が理解しようとしていたものでしたmattが言ったように(そしてあなた)私は私はディレクトリにアクセスしています – KingTim

1

ファイルパスでやっていることはすべて間違っています。 URLを使用して適切に入手し、適切に構成します。例:

let fm = FileManager.default 
let docsurl = try fm.url(for:.documentDirectory, in: .userDomainMask, 
    appropriateFor: nil, create: false) 
let myurl = docsurl.appendingPathComponent(filename) 

ファイルをそのURLに保存します。また、ストリングfilenameを保管してください。後で同じURLでファイルを取得する必要がある場合は、格納されているfilenameで始まり、まったく同じことをやり直してURLを再度作成してください。これで、UIImageを直接URLを使用して読み込むことができます。データを取得してUIImage(data:)にコールするか、URLをpathに変換してUIImage(contentsOfFile:)に呼び出します。

+0

アドバイスをいただきありがとうございます。私はこれを解決しようとしています。私は別のSOソリューションから離そうとしていましたが、現時点では、 – KingTim

+0

私はその機能を更新するために最善を尽くし、オブジェクトのサムネイルをURLに変更しました。私の質問を編集して、私の今のものを表示しました。あなたが何を示唆しているのか?私が改善できるものがあれば教えてください。また、私はあなたの答えの2番目の部分を完全に理解していない、URLを取得します。 'UIImage(contentsOfFile:filePath)'を使うだけでいいですか? – KingTim

+0

ファイルパス全体を保存することはできません。あなたは、私が言ったことをしなければなりません:ファイル名を保存し、URL /パスを再度使用したいときはいつでもそれを再構築してください。 – matt

関連する問題