6

I have a video that is captured with AVCapture, and I'm trying to upload with AFNetworking with Swift.

Code:

let manager = AFHTTPRequestOperationManager()
let url = "http://localhost/test/upload.php"
var fileURL = NSURL.fileURLWithPath(string: ViewControllerVideoPath)
var params = [
    "familyId":locationd,
    "contentBody" : "Some body content for the test application",
    "name" : "the name/title",
    "typeOfContent":"photo"
]

manager.POST( url, parameters: params,
    constructingBodyWithBlock: { (data: AFMultipartFormData!) in
        println("")
        var res = data.appendPartWithFileURL(fileURL, name: "fileToUpload", error: nil)
        println("was file added properly to the body? \(res)")
    },
    success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
        println("Yes thies was a success")
    },
    failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
        println("We got an error here.. \(error.localizedDescription)")
})

The code above fails, I keep getting

was file added properly to the body? false"

note that ViewControllerVideoPath is a string containing the location of the video which is:

"/private/var/mobile/Containers/Data/Application/1110EE7A-7572-4092-8045-6EEE1B62949/tmp/movie.mov" 

using println().... The code above works when I'm uploading a file included in the directory and using:

 var fileURL = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("test_1", ofType: "mov")!)

So definitely my PHP code is fine, and the problem lies with uploading that file saved on the device, what am I doing wrong here?

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
MasterWizard
  • 857
  • 2
  • 15
  • 44
  • How exactly does your upload code fail? Is it uploading absolutely nothing or in some other way (crash etc.)? Did you run a check with NSFileManager to confirm that your file exists before starting upload? – Eugene Apr 25 '15 at 16:48
  • @Eugene the file is played back through a player with the same path... I keep getting from php, "file added to body false".. – MasterWizard Apr 25 '15 at 16:55
  • Seems like this error response from your backend is returned by you manually. Does your backend receive the file? If yes, did you try to write the file somewhere in the backend hard drive to see if the file's encoded properly and can be read by your media player? – Eugene Apr 25 '15 at 18:02
  • @Eugene As I wrote, if when i use the path of the resource movie file when I add it manually in my project as a resource, it uploads successfully, but when I point the path of the resource to something I captured using my phone to the file in the directory of the app, it doesn't work. I tried saving the file in Documents folder instead of temp, and still didn't work. Curiously, the files don't appear in the file manager, but the video player, when i give it the path of the movie file it plays it! – MasterWizard Apr 25 '15 at 18:34
  • Let's try another approach. Try listing the contents of the directory you're saving the recorded file to using this line of code `NSLog(@"Files: %@", [[NSFileManager defaultManager] directoryContentsAtPath: ViewControllerVideoPath]);` after you've completed the recording. See if it shows your file. If it doesn't then the file wasn't properly stored. – Eugene Apr 25 '15 at 19:03
  • @Eugene It was empty, but how if it is empty, the video player got to play the file, btw I have the video playing on the background, and a button on a view onto of it will upload the file. The video player received the same file path! – MasterWizard Apr 25 '15 at 19:09
  • Perhaps you are trying to submit your video while the recording is still in progress? You first need to stop the video recording like this `[videoRecorder stopRecording];`, then wait for it to send you a callback to this method - `-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error`. See if there's anything in the error, if not, then you have successfully recorded a video. Try logging directory contents in this callback. – Eugene Apr 25 '15 at 19:35
  • @Eugene No, the video is records, and I made it go to another view controller, where its being played back, using the same url path. – MasterWizard Apr 25 '15 at 19:56
  • Btw, I found where the error is, the code is in @IBAction, for some reason it doesn't shows me the documents empty, but when i put the code in viewdidload, it shows the files... – MasterWizard Apr 25 '15 at 21:53
  • @AhmedNassar,as you said there wan't be problem while uploading file. the problem is at storing/retriving file. so can you please look over my code and if you have any issue then let me know. – Jatin Patel - JP May 02 '15 at 07:24

2 Answers2

2

Comments don't allow a full explanation so here is more info;

NSBundle.mainBundle() refers to a path in the bundle file The path in the simulator differs from that of the application ... this is not what you want. There are a number of "folders" you can access based on your needs (private or sharable/files that can get backed up to the cloud). NSPathUtils.h gives a breakdown of the paths available. In keeping with conventions used by most, you should probably create a private path under your application path by doing something like;

  - (NSURL *) applicationPrivateDocumentsDirectory{
  NSURL *pathURL = [[self applicationLibraryDirecory]URLByAppendingPathComponent:@"MyApplicationName"];
  return pathURL;

}

  - (NSURL *) applicationLibraryDirecory{

  return [[[NSFileManager defaultManager] URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];

}

You can test if it exists, if not, create it ... then store your video files in this path, and pass this to your AVCapture as the location to store the file.

MDB983
  • 2,444
  • 17
  • 20
1

Here are the code that can do following functionality in swift.

1 : Check weather directory exist or not. if not exist then create directory(Directory has given application name) in document directory folder.

2 : Now we have application directory. so all file that from application will write/read in/from this directory.

   let file = "file.txt"
    let directoryName = “XYZ” // Here “XYZ” is project name.
    var error : NSError?
    let filemgr = NSFileManager.defaultManager()

    let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, 
                .UserDomainMask, true)

    let documentsDirectory = dirPaths[0] as! String 

    var dataPath = documentsDirectory.stringByAppendingPathComponent(directoryName)

    if !NSFileManager.defaultManager().fileExistsAtPath(dataPath) {
        NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil, error: &error)
    } else {
        println("not creted or exist")
    }

Now we have Directory so only need to write/read data from directory.

how to write file in document directory in swift

let filePath = dataPath.stringByAppendingPathComponent(file);
    let text = "some text"

//writing
text.writeToFile(filePath, atomically: false, encoding: NSUTF8StringEncoding, error: nil);

How to read file from document directory.

let filePath = dataPath.stringByAppendingPathComponent(file);
// Read file
let text2 = String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil)

Output : enter image description here

Hope this will help you.

Jatin Patel - JP
  • 3,725
  • 2
  • 21
  • 43