NSURL到NSDATA或数据始终为零

时间:2016-12-08 14:39:49

标签: ios swift swift3 nsdata

我正在尝试通过Alamofire将视频上传到服务器文件,但我无法将“数据”传递给它...总是没有

    var videoURL = NSURL(string: "")
   //returns Optional(file:///private/var/mobile/Containers/Data/Application/1FB40086-228B-4011-A9D4-7874E2EEF9F4/tmp/4A6AAD76-B899-4B67-8E96-925DA4AE9E93.mov)


    let videodata =  NSData(contentsOfFile: (videoURL?.absoluteString)!)
    //nil  
    let url = NSURL(fileURLWithPath: (videoURL?.absoluteString)!)

    let videodata = NSData(contentsOf: url as URL)
    //nil

如果我得到数据会让我这样做:

 Alamofire.upload(multipartFormData: { multipartFormData in
                multipartFormData.append (videodata as! Data, withName: "file", fileName: "file.mov", mimeType: "video/quicktime")
enter code here

EDIT ::

谢谢你们,在你的帮助下,我一直在努力找到这个文件找不到错误,但是我可以看到文件正在我的库中保存,任何线索都可以节省我的一天。

      print (videoURL!)
//returns file:///private/var/mobile/Containers/Data/Application/3F280477-DA16-4A67-AE60-D6247143352E/tmp/1E4AC002-6AD0-41E1-9E0D-A09B697F81F7.mov


       print (videoURL!.path!)
      // returns /private/var/mobile/Containers/Data/Application/3F280477-DA16-4A67-AE60-D6247143352E/tmp/1E4AC002-6AD0-41E1-9E0D-A09B697F81F7.mov


        var videoData = NSData()

        let path = videoURL!.path!
        if FileManager.default.fileExists(atPath: path) {

        }else {
               print("Could not fin file at url: \(videoURL!.path!)")
             // here it throws file not found
        }

2 个答案:

答案 0 :(得分:2)

在Swift 3中,使用原生URLData代替NSURLNSData

if let videoURL = URL(string: urlString), let videodata = try? Data(contentsOf: videoURL) {
     //Add code of Alamofire here
}

答案 1 :(得分:1)

使用absoluteString会在开头返回包含file://的字符串,但您不希望这样。您需要返回URL

的路径
guard let videoPathString = videoURL.path as? String else {
  //handle error here if you can't create a path string
  return
}

var videoData = NSData()

//check if file exists at this path first 
if (NSFileManager.defaultManager().fileExistsAtPath(videoPathString)) {
  videoData = NSData(contentsOfFile: NSString(videoPathString))
} else {
  //if file does not exist at that path, handle here
}