Error Uploading Video to Parse - ios

I am receiving an error when I attempt to upload my video to Parse. The error is client side and is that the variable path is found nil. Perhaps I am declaring this wrong or using pathForResource wrong but I appreciate any help that I would be able to get.
func Upload() {
var path = NSBundle.mainBundle().pathForResource("big_buck_bunny_720p_2mb.mp4", ofType: "mp4")
var videodata: NSData?
videodata = NSData.dataWithContentsOfMappedFile(path!) as? NSData
let file = PFFile(name:"capturedVideo", data:videodata!)
file!.saveInBackground()
}

Related

Swift 3 error handling and variable accessibility

I have a question on how to use the new error handling in Swift.
I'm reading contents of a file into a data object:
var overallData: Data?
//load file contents into data object
let dataFileURL = NSURL(string: fileName)
do {
overallData = try Data(contentsOf: dataFileURL as! URL)
} catch {
print("\(error)")
}
The problem is that I always encounter this error message:
fatal error: unexpectedly found nil while unwrapping an Optional value
The problem is that the overallData object is set as nil. But if I don't define a data variable outside the do-catch,
let dataFileURL = NSURL(string: fileName)
do {
overallData = try Data(contentsOf: dataFileURL as! URL)
} catch {
print("\(error)")
}
Later on, I can't use the overallData object because the system keeps telling me it's a variable not defined yet. So it looks like new variables defined in the do-catch loop can only be locally accessed inside the loop.
Do you know how to solve this problem? I do need to use the overallData object elsewhere.
The following answer assumes your error is with the line:
overallData = try Data(contentsOf: dataFileURL as! URL)
If you are getting the "fatal error" on another line, please update your question.
Your error has nothing to do with the do/catch/try.
Your problem is the force unwrapping of dataFileURL which is nil.
Your problem is this line:
let dataFileURL = NSURL(string: fileName)
This is returning nil because fileName isn't a valid URL.
Assuming fileName is a path to a local file, you need to do:
let dataFileURL = URL(fileURLWithPath: fileName)
Also note the use of URL instead of NSURL. There is no sense in using NSURL in Swift 3.

Get metadata from mp3 file with URL (swift)

I'm new in swift and i would like to get data from a mp3 file located on a server, ( i used an URL, exemple : http://myserver.eu/file.mp3 ).
i used some tuto, like http://geekyviney.blogspot.com/2015/02/extracting-data-like-thumbnail-images.html ( it's working with a local file and i'm trying to make it work with a file from an url)
i got a exception :
Thread 1: EXC_BAD_INSTRUCTION(code=EXC_I1386_INVOP, subcode=0x0
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
I suppose that pathForResource is only for local file ? thanks for your help
var filePath = NSBundle.mainBundle().pathForResource("http://servername.eu/filename", ofType: "mp3")
var fileUrl = NSURL(fileURLWithPath: filePath!)
var asset = AVAsset.assetWithURL(fileUrl) as AVAsset
You're right, pathForResource is used to access files locally in the application bundle.
To load data from URLs with http scheme use this syntax
let urlString = "http://servername/filename"
let serverURL = NSURL(string: urlString)!
if let asset = AVAsset.assetWithURL(serverURL) as? AVAsset {
// do something with the asset
}
Swift 3 version:
let urlString = "http://servername/filename"
if let serverURL = URL(string: urlString) {
let asset = AVAsset(url: serverURL)
// do something with the asset
}
Ow and don't forget to add the correct import
import AVFoundation

UIImage Download Returning nil and Crashing App (Swift)

I have an image url string:
var remoteImage: String = "http://server.com/wall-e.jpg"
I then construct a UIImage to download on a separate thread using Grand Central Dispatch with remoteImage as the NSURL string parameter:
let getImage = UIImage(data: NSData(contentsOfURL: NSURL(string: remoteImage)!)!)
When it is finished and I return back to the main thread, I have it save internally:
UIImageJPEGRepresentation(getImage, 1.0).writeToFile(imagePath, atomically: true)
On Wi-fi and LTE it downloads fine, but when testing edge cases such as on an Edge network (no pun intended), I inconsistently get the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Now I thought I would be safe by making sure that it wasn't nil by adding in:
if getImage != nil { ... }
But it didn't seem to make a difference. It still gets the error and highlights the let getImage as written above. What am I doing wrong here? Should I be checking nil in a different manner or method?
I would recommend you to use AsyncRequest to fetch and download the image and saved it locally.
As you didn't posted any of code of your problem.
So i am posting a sample working for me.
Sample for downloading and saving image locally
var url = NSURL(string : "http://freedwallpaper.com/wp-content/uploads/2014/09/Tattoo-Girl.jpg")
let urlrequest = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(urlrequest, queue: NSOperationQueue.mainQueue(), completionHandler: {
response ,data , error in
if error != nil
{
println("error occurs")
}
else
{
let image = UIImage(data: data)
/* Storing image locally */
var documentsDirectory:String?
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
println(paths)
if paths.count > 0{
documentsDirectory = paths[0] as? String
var savePath = documentsDirectory! + "/bach.jpg"
NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
self.bach.image = UIImage(named: savePath)
}
}
})
}
The error, does, in fact lie on the line:
let getImage = UIImage(data: NSData(contentsOfURL: NSURL(string: remoteImage)!)!)
The reason is that it's not the UIImage that is initially returning nil, it is probably NSData returning nil. You could check if NSData is returning nil, and then create the UIImage object instead.
EDIT: What the particular line of code is doing is it is assuming that NSData is always returning a non-nil value, which may not be true when you are not connected. When you're not connected, it gets a nil value, which you are trying to say will never be a nil value using the exclamation mark (!).
I suggest you read further on how Swift works. For this particular example, take a look at what the exclamation marks actually mean in Swift: What does an exclamation mark mean in the Swift language?

Why can't I upload images to Parse? Anybody know of a different way to do this?

I just need to upload some images, and I feel like my simple code should work, but for some reason it isn't. I'm getting an error saying that my object exceeds the Parse.com limit of 128kb... And I'm sure it doesn't actually exceed that. Code is here.
override func viewDidLoad() {
super.viewDidLoad()
func addCards(urlString:String) {
var newCard = PFObject(className: "Cards")
let url = NSURL(string: urlString)
let urlRequest = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue(), completionHandler: {
response, data, error in
newCard["image"] = data
newCard.save()
})
}
addCards("http://image.com/image")
You shouldn't just be pushing the image data direct into the object. Instead, create a PFFile instance with the data and set that. Then, save the file and the card at the same time (using saveAll).
See the following link from Parse documentations which has a code snippet and also the reason for using PFFile as suggested by Wain:
https://www.parse.com/docs/ios/guide#files
According to Parse documentation: You can easily store images by converting them to NSData and then using PFFile. Suppose you have a UIImage named image that you want to save as a PFFile:
let imageData = UIImagePNGRepresentation(image)
let imageFile = PFFile(name:"image.png", data:imageData)
var userPhoto = PFObject(className:"UserPhoto")
userPhoto["imageName"] = "My trip to Hawaii!"
userPhoto["imageFile"] = imageFile
userPhoto.saveInBackground()

OSStatus error 2003334207 when using AVAudioPlayer

I am trying to play an MP3 file (works when played via VLC/iTunes) when a button is pressed. Here is my code:
var audioPlayer: AVAudioPlayer!
#IBAction func playEpisode(sender: AnyObject) {
println("now playing")
let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0)
let data: CDEpisode = fetchedResultsController.objectAtIndexPath(indexPath!) as! CDEpisode
var err: NSError?
let url = NSURL(string: data.localPath)
println("The url is \(url)")
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &err)
if audioPlayer == nil {
if let e = err {
println(e.localizedDescription)
}
}
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
}
Here is the log:
now playing
The url is Optional(file:///var/mobile/Containers/Data/Application/4747A71E-A63F-4EFC-B2DF-8B361361080B/Documents/serial-s01-e12.mp3)
The operation couldn’t be completed. (OSStatus error 2003334207.)
fatal error: unexpectedly found nil while unwrapping an Optional value
The EXC_BREAKPOINT happens on the audioPlayer.delegate = self.
Other threads on StackoOverflow do not help. Any ideas?
Thanks
Edit: I have tried passing a localURL to contentsOfURL (instead of a CDEpisode object) and it still fails.
This is probably caused by trying to load a file that doesn't exist. If that helps someone adding the call to url.checkResourceIsReachable() will log more descriptive message.
Example code:
do {
let url = URL(fileURLWithPath: dbObject.path)
let isReachable = try url.checkResourceIsReachable()
// ... you can set breaking points after that line, and if you stopped at them it means file exist.
} catch let e {
print("couldnt load file \(e.localizedDescription)")
}
It looks like your trying to unwrap a variable that has a nil value. You should safely unwrap your variables to prevent this.
if let data: CDEpisode = fetchedResultsController.objectAtIndexPath(indexPath!) as! CDEpisode
{
var err: NSError?
let url = NSURL(string: data.localPath)
println("The url is \(url)")
//rest of code
}
You will still need to figure out why it is returning nil but this is a safer way to unwrap variables and prevent crashing as there would need to be more context to resolve that issue.
Some questions to look into:
Are you sure the fetchedResultsController is returning an object at
all?
Are you sure it is of CDEpisode?
try this one
var player: AVAudioPlayer = AVAudioPlayer()
#IBAction func playX(_ sender: Any) {
let urlstring = "https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
let url = URL(string: urlstring)
let data = try! Data(contentsOf: url!)
player = try! AVAudioPlayer(data: data)
player.prepareToPlay()
player.volume = 1.0
player.play()
}
You're checking if audioPlayer is nil but then you go on to use it as if it wasn't anyway. You probably want something like:
if audioPlayer == nil {
if let e = err {
println(e.localizedDescription)
}
} else {
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
}
And do something to actually handle the error case rather than just printing the error.
In my case I was having the same issue and I found out that I needed to set this before start recording
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
Hope it helps anyone
I also got this problem, after checking up the audio file url, found that it is stored in Cache directory. so audio player probably couldn't find audio file according to your "url".
please ensure, the url path is under Document directory.
As others have said, the audio player couldn't find the file.
This helped me: Document directory path change when rebuild application
Basically, you cannot load files with an absolute reference, as the sandbox environment regenerates the absolute file url each time. So you will need to add a small bit of code (see above) to get the correct urls to use.

Resources