String(data:data,encoding:NSUTF8StringEncoding)返回nil

时间:2015-12-22 13:20:04

标签: swift video encoding nsdata

我正在使用JSQMessage并且削减发送和保存视频文件

if (mediaType == kUTTypeVideo as String) || (mediaType ==  kUTTypeMovie as String) {

        let movieURL = info[UIImagePickerControllerMediaURL] as? NSURL
        let videoMediaItem = JSQVideoMediaItem.init(fileURL: movieURL, isReadyToPlay: true)
        let message = JSQMessage(senderId: self.senderId, senderDisplayName: senderDisplayName, date: NSDate(), media: videoMediaItem)
        self.saveMediaToParse(message, data: NSData(contentsOfURL: movieURL!)!, fileName:"videoFile")
        self.messages += [message]
        self.publishMessageToChannel(message)
        self.finishSendingMessage()
    }  


func saveMediaToParse(message:JSQMessage, data:NSData, fileName:String) {

    let imageFile = PFFile.init(data: data)
    let msg = PFObject(className: "test")
    msg["senderId"] = message.senderId
    msg[fileName] = imageFile
    msg["senderDisplayName"] = message.senderDisplayName
    msg["user"] = PFUser.currentUser()

    msg.saveInBackgroundWithBlock { (success, error) -> Void in
        if(error != nil) {
            NSLog("error: %@",(error?.localizedDescription)!)
        }
    }
}

当我试图从数据中获取视频URL作为字符串时,我得到了nil值。我做错了什么?

message["videoFile"].getDataInBackgroundWithBlock({ (data, error) -> Void in
                        if let data = data where error == nil {
                            **let dataStr = String(data: data, encoding: NSUTF8StringEncoding)**

                            let movieUrl = NSURL(string: dataStr!)
                            let videoMediaItem = JSQVideoMediaItem.init(fileURL: movieUrl, isReadyToPlay:true)
                            jsqMessage = JSQMessage(senderId:message["senderId"] as! String, displayName: message["senderDisplayName"] as! String, media: videoMediaItem)
                            self.messages.append(jsqMessage)
                            self.collectionView?.reloadData()
                            self.scrollToBottomAnimated(true)
                        }
                    })
                }
                self.messages.append(jsqMessage)

1 个答案:

答案 0 :(得分:1)

结束了     让dataStr = NSTemporaryDirectory()+“temp.mov”     data.writeToFile(dataStr,atomically:true)     让movieUrl = NSURL(fileURLWithPath:dataStr)

而不是     let dataStr = String(data:data,encoding:NSUTF8StringEncoding)**