I just haven't "info" in Swift imagePickerController so I don't know how get url and convert it to data to send to web-service.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var videoDataURL = info[UIImagePickerControllerMediaURL] as! NSURL!
var videoFileURL = videoDataURL.filePathURL
var video = NSData.dataWithContentsOfMappedFile("\(videoDataURL)")
}
Xcode 8.3 • Swift 3.1
Swift 2
You should use if let to unwrap your optionals. Also
NSData.dataWithContentsOfMappedFile
was deprecated iOS8. Try using NSData method initializer contentsOfURL:Note: You need also to change the didFinishPickingMediaWithInfo declaration from
[NSObject : AnyObject]
to[String : AnyObject]
as mentioned by Rob the data can be really large but instead of copying the file you should move the file to the documents folder as follow:
There are a couple of issues:
Consider this line:
This does a forced unwrapping of
info[UIImagePickerControllerMediaURL]
(which is bad, because if it wasnil
, the app would crash) and that casts it as an implicitly unwrapped optionalNSURL!
. That doesn't make sense. Just do a conditional unwrapping (and unwrap to aNSURL
, not aNSURL!
):The next line calls
filePathURL
:If you wanted a file URL, you already have one, so no conversion is needed, but instead just use
videoDataURL
. If you really wanted a path, you'd usepath
method:Frankly, Apple is trying to shift us away from using string paths, so just use the original
videoDataURL
and avoid the use of bothpath
andfilePathURL
.You are using
dataWithContentsOfMappedFile
:If you really wanted to use
dataWithContentsOfMappedFile
, the proper Swift syntax is:But
dataWithContentsOfMappedFile
deprecated, so you should instead use:Or, bypassing that
videoPath
altogether, you could:Obviously, those
try
renditions should be done within ado
block with acatch
block.By the way, as you'll see in all of my above examples, one should use
let
where possible.--
Quite frankly, I would advise against loading it into a
NSData
at all. Just copy it withNSFileManager
, which is a more efficient use of memory. If the video is long, it could be quite large, and you should avoid loading the whole thing into memory at any given point in time.So you could:
If you're uploading this to a web service, you'd then use a
NSURLSessionUploadTask
, using file or stream options. The construction of this request is a separate question, but hopefully you get the idea: With large assets like photos or, especially, videos, don't instantiate aNSData
with the asset if you can possibly avoid it.