1
votes

I can't seem to convert NSURL to NSData. The NSURL appears when printed out, but then when I try to convert it to NSData, the audioData variable keeps returning nil.

func mediaPicker(mediaPicker: MPMediaPickerController!, didPickMediaItems mediaItemCollection: MPMediaItemCollection!)
{
    selectedSong = mediaItemCollection.items[0] as MPMediaItem

    songUrl = selectedSong.valueForProperty(MPMediaItemPropertyAssetURL) as? NSURL
    println("\(songUrl)")

    audioData = NSData(contentsOfURL: songUrl) as NSData
    println("\(audioData)")
}

Edited Code to Catch the Error

songUrl is the URL address of a song located on my iPod library

    var errorPointer:NSErrorPointer!
    audioData = NSData(contentsOfURL: songUrl, options: NSDataReadingOptions.DataReadingMappedAlways, error: errorPointer)
    if audioData == nil
    {
        println("\(errorPointer)")
    }

This code prints the error: "fatal error: unexpectedly found nil while unwrapping an Optional value" onto my console

Edit #2

Using the format in the error format in the answer below, I now get the error:

An Error Occurred: Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x146f4a90 {NSURL=ipod-library://item/item.m4a?id=3210273692689505570}

1
use NSData(contentsOfURL: options: error:) and let us know what the error returned is. - Michael Dautermann
Thanks for the reply...I wrote your code like so: audioData = NSData(contentsOfURL: songUrl, options: NSDataReadingOptions.DataReadingMappedAlways, error: NSErrorPointer()) although i'm not sure I initialized the errorpointer correctly, there wasn't any error printout on my console. - user3353890
There shouldn't be any output on the console. You need to log error. - rdelmar
@rdelmar cool, thanks for the tip, I'll try that out and get back to you - user3353890
Yes, do not declare "NSErrorPointer()" within the contentsOfURL call. Declare it outside, pass it in via contentsOfURL as a parameter and then print out the error if audioData comes back nil. - Michael Dautermann

1 Answers

0
votes

The URL is only appropriate with AVFoundation, NSData won't be able to do a thing with the NSURL.
From Apple docs:

"Usage of the URL outside of the AV Foundation framework is not supported."

Example of how to code the error parameter:

var error: NSError?
audioData = NSData(contentsOfURL: songUrl, options: .DataReadingUncached, error: &error)

if audioData == nil {
    if let unwrappedError = error {
        println("An Error Occurred: \(unwrappedError)")
    }
}