NSURL to NSDATA or Data is always nil

夙愿已清 提交于 2019-12-12 03:43:21

问题


I am trying to upload a video to a server file through Alamofire but I couldn't get the "data" going to be passed..its always nil

    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

If I get data would lead a way for me to do this:

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

EDIT::

thank you guys, with your help I have struggled my way out of there to this file not found error, but I can see the file is being saved in my gallery, any clue would save my day.

      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
        }

回答1:


In Swift 3 use native URL and Data instead of NSURL and NSData.

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



回答2:


Using absoluteString returns a string that includes file:// at the beginning and you don't want that. You need to return the path of the 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
}


来源:https://stackoverflow.com/questions/41042034/nsurl-to-nsdata-or-data-is-always-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!