AWS SDK IOS - uploadRequest is Remains nil - ios

NSString* path = [[NSBundle mainBundle] pathForResource:#"myTestFile"
ofType:#"txt"];
AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.bucket = S3BucketName;
uploadRequest.key = #"myTestFile.txt";
uploadRequest.body = [NSURL fileURLWithPath:path];
AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];
[[transferManager upload:uploadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor]
withBlock:^id(AWSTask *task) {
if (task.error) {
if ([task.error.domain isEqualToString:AWSS3TransferManagerErrorDomain]) {
switch (task.error.code) {
case AWSS3TransferManagerErrorCancelled:
case AWSS3TransferManagerErrorPaused:
break;
default:
NSLog(#"Error: %#", task.error);
break;
}
} else {
// Unknown error.
NSLog(#"Error: %#", task.error);
}
}
if (task.result) {
AWSS3TransferManagerUploadOutput *uploadOutput = task.result;
NSLog(#"The file uploaded successfully");
// The file uploaded successfully.
}
return nil;
}];
Cannot Able to upload a File by doing This . . . all the objects staying nil after application launch . . . uploadRequest as well as transferManager . . .

Related

Save photo to camera roll and return url

I am trying to save a base64 image to camera roll and return the url for the saved image. The code works in so far as I have succeeded in saving to camera roll but I am seeing an error and no URL is returned. The error is:
Error Domain=NSCocoaErrorDomain Code=-1 "(null)"
My code is:
- (void)saveImageDataToLibrary:(CDVInvokedUrlCommand*)command
{
__block CDVPluginResult* result = nil;
NSData* imageData = [NSData dataFromBase64String:[command.arguments objectAtIndex:0]];
UIImage* image = [[[UIImage alloc] initWithData:imageData] autorelease];
__block PHObjectPlaceholder *placeholderAsset = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *newAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
placeholderAsset = newAssetRequest.placeholderForCreatedAsset;
} completionHandler:^(BOOL success, NSError *error) {
if(success){
NSLog(#"worked");
PHAsset *asset = [self getAssetFromlocalIdentifier:placeholderAsset.localIdentifier];
PHContentEditingInputRequestOptions *options = [[PHContentEditingInputRequestOptions alloc] init];
options.networkAccessAllowed = YES; //download asset metadata from iCloud if needed
[asset requestContentEditingInputWithOptions:options
completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
NSURL *assetURL = contentEditingInput.fullSizeImageURL;
NSString* url = [assetURL absoluteString];
NSLog(#"our result is: %#", url);
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:url];
[self invokeCallback:command withResult:result];
}];
} else {
NSLog(#"Error: %#", error);
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description];
[self invokeCallback:command withResult:result];
}
}];
}
- (void) invokeCallback:(CDVInvokedUrlCommand *)command withResult:(CDVPluginResult *)result {
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
Try to use:
PHContentEditingOutput
That object has a property called: renderedContentURL
Use that to get the appropriate URL of your PHAsset.
So to get the URL, your code should look like this:
PHContentEditingOutput *contentEditingOutput = [[PHContentEditingOutput alloc] initWithContentEditingInput:YOUR_PHCONTENTEDITING_INPUT];
NSURL *myPHAssetURL = [contentEditingOutput renderedContentURL];

Can anyone suggest me the effective way to deal with s3 upload fail because of timezone difference issue?

I tried both SDK version V1 and V2. I have application in which I am posting user's photo/video on s3. When the device's timezone is not set to automatic,many times uploading fails because of timezone difference. I am not able to catch this error or exception consistently. didFailWithError never get called for timezone difference,I have to catch it in didCompleteWithResponse.
I used below code for 1.7.1 SDK.
[AmazonLogger verboseLogging];
AmazonS3Client *s3 = [[AmazonS3Client alloc] initWithAccessKey:AWS_AccessKey withSecretKey:AWS_SecretKey];
s3.endpoint=[AmazonEndpoints s3Endpoint:US_EAST_1];
#try
{
por = [[S3PutObjectRequest alloc] initWithKey:[aStrAWSPath lastPathComponent] inBucket:aStrFolder];
por.contentType = aStrType;
por.data = aDataToPost;
por.delegate=self;
[por setCannedACL:[S3CannedACL publicReadWrite]];
[s3 putObject:por];
aWSTotalBytesWritten = 0.0;
}
#catch (AmazonServiceException *exception)
{
NSLog(#"%#",exception.description);
}
#catch (AmazonClientException *exception)
{
NSLog(#"%#",exception.description);
}
-(void)request:(AmazonServiceRequest *)request didCompleteWithResponse:(AmazonServiceResponse *)response
{
if(response.exception==nil)
{
//Success
}
else
{
if([response.exception isKindOfClass:[AmazonServiceException class]])
{
AmazonServiceException *aServiceExceptionObj=(AmazonServiceException *)response.exception;
if([aServiceExceptionObj.errorCode isEqualToString:#"RequestTimeTooSkewed"])
{
//Please check your date&time settings.It should be set to automatically.
}
}
}
-(void)request:(AmazonServiceRequest *)request didFailWithError:(NSError *)error
{
NSLog(#"AWSError : %#", error.description);
}
In AWSiOSSDKv2,I used below code,
AWSServiceConfiguration *aConfigObj=[AWSServiceConfiguration configurationWithRegion:AWSRegionUSEast1 credentialsProvider:CustomCredentialsProviderObj];
AWSS3TransferManager *transferManager = [[AWSS3TransferManager alloc] initWithConfiguration:aConfigObj identifier:#"testUplaod"];
AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.bucket = #"testsdkv2/testsdkv2internal";
uploadRequest.key = [NSString stringWithFormat:#"%d.jpg",(int)[[NSDate date]timeIntervalSince1970]];
NSURL *aUrlObj=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"test" ofType:#"jpg"]];
uploadRequest.body = aUrlObj;
uploadRequest.ACL=AWSS3BucketCannedACLPublicReadWrite;
uploadRequest.contentType=#"image/jpeg";
[[transferManager upload:uploadRequest] continueWithBlock:^id(BFTask *task) {
if (task.error)
{
//Not uploaded
}
if (task.result)
{
// The file uploaded successfully.
}
return nil;
}];
On the worst of hypothesis, try using AFNetworking and set custom header fields, including date. It is also faster. Import the AFNetworking library using cocoa pods and upload your files like this:
NSString *fileContentTypeStr = //file type string;
NSURL *imageUploadURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:#"image"]];
[data writeToURL:self.imageUploadURL atomically:YES];
AWSS3GetPreSignedURLRequest *getPreSignedURLRequest = [AWSS3GetPreSignedURLRequest new];
getPreSignedURLRequest.bucket = //Bucket;
getPreSignedURLRequest.key = //Key Name;
getPreSignedURLRequest.HTTPMethod = AWSHTTPMethodPUT;
getPreSignedURLRequest.expires = [NSDate dateWithTimeIntervalSinceNow:3600];
getPreSignedURLRequest.contentType = fileContentTypeStr;
[[[AWSS3PreSignedURLBuilder defaultS3PreSignedURLBuilder] getPreSignedURL:getPreSignedURLRequest]
continueWithBlock:^id(BFTask *task) {
if (task.error) {
NSLog(#"Error: %#",task.error);
} else {
NSURL *presignedURL = task.result;
NSMutableURLRequest *URLRequest = [NSMutableURLRequest requestWithURL:presignedURL];
[URLRequest setValue:fileContentTypeStr forHTTPHeaderField:#"Content-Type"];
//Set your custom header field here
URLRequest.HTTPMethod = #"PUT";
URLRequest.HTTPBody = imageData;
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress;
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:URLRequest progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if(error)
{
UIAlertView *b = [[UIAlertView alloc] initWithTitle: NSLocalizedString(#"An error ocurred",nil) message: [error userInfo][#"error"] delegate: self cancelButtonTitle:NSLocalizedString(#"Dismiss",nil) otherButtonTitles: nil];
[b show];
}
}];
[progress addObserver:self
forKeyPath:#"fractionCompleted"
options:NSKeyValueObservingOptionNew
context:NULL];
[uploadTask resume];
}
return nil;
}];
I managed to resolve this issue by setting "ClockSkew" to the difference between my UTC time and server's UTC time by taking Managing-Device-Time-with-the-AWS-Mobile-SDKs in refference.
[NSDate aws_setRuntimeClockSkew:aTimeInterval];

Getting image URL from bucket Amazon Web Service iOS after uploading

I have an image that I'm uploading to my bucket in AWS this way:
BFTask *task = [BFTask taskWithResult:nil];
[[task continueWithBlock:^id(BFTask *task) {
self.URL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:#"test"]];
NSData *data = UIImagePNGRepresentation(image);
//NSMutableString *dataString = [NSMutableString new];
[data writeToURL:self.URL atomically:YES];
return nil;
}]continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task) {
self.uploadRequest1 = [AWSS3TransferManagerUploadRequest new];
self.uploadRequest1.bucket = S3BucketName;
self.uploadRequest1.key = S3KeyUploadName1;
self.uploadRequest1.body = self.URL;
return nil;
}];
AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];
[[transferManager upload:self.uploadRequest1] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task) {
if (task.error != nil) {
if( task.error.code != AWSS3TransferManagerErrorCancelled
&&
task.error.code != AWSS3TransferManagerErrorPaused
)
{
NSLog(#"Upload Failed!");
}
} else {
self.uploadRequest1 = nil;
NSLog(#"Uploaded!");
}
return nil;
}];
The code for uploading the image works just fine. When I open my bucket I see the image there.
Now what I want to do is to get the URL of that image, is there a way to get the URL without getting the image again?
You don't get it, you create it like:
https://s3.amazonaws.com/BUCKET_NAME/FILE_NAME.jpg
AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.body = [NSURL fileURLWithPath:filePath];
uploadRequest.key = fileName;
uploadReuest.bucket = S3BucketName;
[uploadRequest setACL:AWSS3ObjectCannedACLPublicRead];
Above Answer is right but you must have to set "ACL" to uploadRequest.
In your Question,you are forget to set "ACL".
Thanks
I was able to get the path from Amazon S3 -> Bucket -> Folder -> Image file -> Properties and on right side, you will see something like this..

How to upload a UIImage to S3 with AWS iOS SDK v2

The README page in Github (https://github.com/aws/aws-sdk-ios-v2) already has an example to upload an image, from the file path URL:
AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.bucket = yourBucket;
uploadRequest.key = yourKey;
uploadRequest.body = yourDataURL; // <<<< this is a NSURL
uploadRequest.contentLength = [NSNumber numberWithUnsignedLongLong:fileSize];
But, what if I only have a UIImage in memory (without file path)?
Is it possible to upload a UIImage (or it's NSData) to S3 using the SDK?
Would it be easier to manually use the HTTP API (using something like AFNetworking)?
Even though AWSiOSSDKv2 doesn't support uploading images from memory, you can save it as a file and then upload it.
//image you want to upload
UIImage* imageToUpload = [UIImage imageNamed:#"imagetoupload"];
//convert uiimage to
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", dateKey]];
[UIImagePNGRepresentation(imageToUpload) writeToFile:filePath atomically:YES];
NSURL* fileUrl = [NSURL fileURLWithPath:filePath];
//upload the image
AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.body = fileUrl;
uploadRequest.bucket = AWS_BUCKET_NAME;
uploadRequest.key = #"yourkey";
uploadRequest.contentType = #"image/png";
[[transferManager upload:thumbNailUploadRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task) {
if(task.error == nil) {
NSLog(#"woot");
}
return nil;
}];
It seems that AWSiOSSDKv2 don't have support to upload images from memory at this moment :(
From a Github issue:
The decision to accept only file NSURLs was driven by the following
factors:
Since v1, the pause / resume features require the input to be
files. It's not possible to recover NSData and retry the transfer when
the app is killed.
The background transfer on iOS 7 and above only
supports files. Currently, we don't support background transfer, but
we are planning to support it in the future. We considered accepting
an NSData and internally persisting the data to a temporary directory.
We decided not to include this in 2.0 release because if the NSData is
backed by a file, it doubles the disk usage for the data. Also,
developers have to deal with disk related errors when using
S3TransferManager. Even though we decided not to accept NSData in 2.0
release, we are open for your feedback. If this is a feature you want
to see in the future release, please create a new issue with the
feature request.
```
You can apparently do it with "presigned URLs"
- (void)uploadImageToS3: (UIImage *)image {
NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
AWSS3GetPreSignedURLRequest *getPreSignedURLRequest = [AWSS3GetPreSignedURLRequest new];
getPreSignedURLRequest.bucket = #"bucket-name";
getPreSignedURLRequest.key = #"image-name.jpg";
getPreSignedURLRequest.HTTPMethod = AWSHTTPMethodPUT;
getPreSignedURLRequest.expires = [NSDate dateWithTimeIntervalSinceNow:3600];
NSString *fileContentTypeString = #"text/plain";
getPreSignedURLRequest.contentType = fileContentTypeString;
[[[AWSS3PreSignedURLBuilder defaultS3PreSignedURLBuilder] getPreSignedURL:getPreSignedURLRequest] continueWithBlock:^id(AWSTask *task) {
if (task.error) {
NSLog(#"Error: %#", task.error);
} else {
NSURL *presignedURL = task.result;
NSLog(#"upload presignedURL is \n%#", presignedURL);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:presignedURL];
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
[request setHTTPMethod:#"PUT"];
[request setValue:fileContentTypeString forHTTPHeaderField:#"Content-Type"];
NSURLSessionUploadTask *uploadTask = [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"Upload errer: %#", error);
}
NSLog(#"Done");
}];
[uploadTask resume];
}
return nil;
}];
}
Documented in the S3 docs for v2 SDK at http://docs.aws.amazon.com/mobile/sdkforios/developerguide/s3transfermanager.html#use-pre-signed-urls-to-transfer-objects-in-the-background
Its a bit of a mess with nested completion blocks, but the gist is you request a url, then when that returns you start an upload task. This was for a prototype test, not polished code. You should check the status code on the upload instead of just the error.
This is an updated answer so people don't have to figure it out themselves (like me) :D
Import the proper files (download it here)
#import <AWSCore/AWSCore.h>
#import <AWSS3TransferManager.h>
.m
- (void)viewDidLoad {
[super viewDidLoad];
AWSCognitoCredentialsProvider *credentialsProvider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1
identityPoolId:#"us-east-1:*******-******-*****-*****-*****"];
AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1
credentialsProvider:credentialsProvider];
AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;
}
I used a button to know when the user wants to upload the file
- (void)upload{
//convert uiimage to
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#".png"]];
[UIImagePNGRepresentation(YOUR_UIIMAGE) writeToFile:filePath atomically:YES];
NSURL* fileUrl = [NSURL fileURLWithPath:filePath];
//upload the image
AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.body = fileUrl;
uploadRequest.bucket = #"YOUR_BUCKET_NAME";
uploadRequest.key = #"YOUR_FOLDER_NAME (if you have one)/NEW_IMAGE_NAME.png";
uploadRequest.contentType = #"image/png";
uploadRequest.ACL = AWSS3BucketCannedACLPublicRead;
AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];
[[transferManager upload:uploadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor]
withBlock:^id(AWSTask *task) {
if (task.error != nil) {
NSLog(#"%s %#","Error uploading :", uploadRequest.key);
}else { NSLog(#"Upload completed"); }
return nil;
}];
}
Helpfull links:
AWS Documnetion
YouTube Video
Hopefully this helps someone out!
In the current version of the SDK you can use AWSS3TransferUtility and then it does everything for you.
func uploadData() {
let data: Data = Data() // Data to be uploaded
let expression = AWSS3TransferUtilityUploadExpression()
expression.progressBlock = {(task, progress) in
DispatchQueue.main.async(execute: {
// Do something e.g. Update a progress bar.
})
}
var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
completionHandler = { (task, error) -> Void in
DispatchQueue.main.async(execute: {
// Do something e.g. Alert a user for transfer completion.
// On failed uploads, `error` contains the error object.
})
}
let transferUtility = AWSS3TransferUtility.default()
transferUtility.uploadData(data,
bucket: "YourBucket",
key: "YourFileName",
contentType: "text/plain",
expression: expression,
completionHandler: completionHandler).continueWith {
(task) -> AnyObject! in
if let error = task.error {
print("Error: \(error.localizedDescription)")
}
if let _ = task.result {
// Do something with uploadTask.
}
return nil;
}
}
Hi you can sand image without saving image to the temporary folder in the iPhone Amazon iOS v2 gives such option as well.
In this code logFile.body it is NSData.
This code will help you my friend.
AWSS3PutObjectRequest *logFile = [AWSS3PutObjectRequest new];
logFile.bucket = uploadTokenData_.bucket;
logFile.key = key;
logFile.contentType = contentType;
logFile.body = data_;
logFile.contentLength = [NSNumber numberWithInteger:[data_ length]];
AWSS3 *S3 = [[AWSS3 alloc] initWithConfiguration:[AWSCredentialsProvider runServiceWithStsCredential]];
AWSS3TransferManager *transferManager = [[AWSS3TransferManager alloc] initWithS3:S3];
[[transferManager.s3 putObject:logFile] continueWithBlock:^id(BFTask *task)
{
NSLog(#"Error : %#", task.error);
if (task.error == nil)
{
NSLog(#"Uploadet");
}
}
With AWSS3TransferUtility you can upload any data type, also AWSS3TransferManagerUploadRequest is deprecated now, here is the code sample to upload jpeg but can be converted for any data type:
Code sample

Save recorded video from AVFoundation

I am not able to save the recorder video from AVFoundation... In didfinishcapture I check if file exists in the temporary folder, code always returns NO.
Also, this warning is printed when i stop the recording:
"cannot be saved to the saved photos album: Error Domain=NSOSStatusErrorDomain Code=2 "This movie could not be played." UserInfo=0x1c5696c0 {NSLocalizedDescription=This movie could not be played.}"
#define OP_PATH [NSTemporaryDirectory() stringByAppendingPathComponent:[#"movie" stringByAppendingPathExtension:#"mov"]]
- (IBAction) startSession:(id)sender
{
if(! self.captureSession)
{
//Session
self.captureSession = [[AVCaptureSession alloc] init];
//self.captureSession.sessionPreset = AVCaptureSessionPresetMedium;
//Layer of own view
CALayer *viewLayer = self.captureView.layer;
//AVCaptureVideoPreviewLayer
AVCaptureVideoPreviewLayer *avCaptureLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
avCaptureLayer.frame = self.captureView.bounds;
[self.captureView.layer addSublayer:avCaptureLayer];
//AVCaptureDevice
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *err = nil;
//Output - Image
self.stillImgOutput = [[AVCaptureStillImageOutput alloc] init];
[self.stillImgOutput setOutputSettings:[NSDictionary dictionaryWithObjectsAndKeys:
AVVideoCodecJPEG, AVVideoCodecKey,
nil]];
[self.captureSession addOutput:self.stillImgOutput];
//Output - Video
self.movieOutput = [[AVCaptureMovieFileOutput alloc] init];
// NSString* key = (NSString*)kCVPixelBufferBytesPerRowAlignmentKey;
//
// NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
//
// NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
if([self.captureSession canAddOutput:self.movieOutput])
{
NSLog(#"Movie out put added");
[self.captureSession addOutput:self.movieOutput];
}
else
{
NSLog(#"Cannot add movie out put");
}
//Input
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&err];
if(! input)
{
NSLog(#"Error no camera");
return;
}
if([self.captureSession canAddInput:input])
{
[self.captureSession addInput:input];
}
else
{
NSLog(#"Cannot add input. Check Output Settings");
}
}
if(! [self.captureSession isRunning])
{
[self.captureSession startRunning];
}
else
{
NSLog(#"Session already running");
}
}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
NSLog(#"Did stop recording to - %# \n Any error ? - %#", outputFileURL, [error description]);
if([[NSFileManager defaultManager] fileExistsAtPath:[outputFileURL absoluteString]])
{
NSLog(#"YES file exists");
}
else
{
NSLog(#"NO File does not exist");
}
if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([outputFileURL absoluteString]))
{
NSLog(#"YES file is compatible to be saved in Album");
UISaveVideoAtPathToSavedPhotosAlbum([outputFileURL absoluteString], self, #selector(video:didFinishSavingWithError:contextInfo:), nil);
}
else
{
NSLog(#"NO File is not compatible");
}
}
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
if(! error)
{
NSLog(#"Video Saved to Album");
}
else
{
NSLog(#"Video not saved to Album - %#", [error description]);
}
NSError *er;
[[NSFileManager defaultManager] removeItemAtPath:OP_PATH error:&er];
if(! er)
{
NSLog(#"Temporary file deleted");
}
else
{
NSLog(#"Temporary file not deleted - %#", [er description]);
}
}
You are missing the following piece of code. See below
//Use timestamp to get new movie name everytime you capture
NSString *timeStamp = [NSString stringWithFormat:#"%0.0f",[[NSDate date] timeIntervalSince1970] * 1000];
NSString *movieOutputUrl =[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mov",timeStamp]];
NSURL *url = [NSURL URLWithString:movieOutputUrl];
[self.movieOutput startRecordingToOutputFileURL:url recordingDelegate:self];
I hope it helps.
Cheers.
- (void)captureOutput:(AVCaptureFileOutput *)captureOutputdidFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
if (error)
{
NSLog(#"%#", error);
}
UIBackgroundTaskIdentifier backgroundRecordingID = [self backgroundRecordingID];
[self setBackgroundRecordingID:UIBackgroundTaskInvalid];
[[[ALAssetsLibrary alloc] init] writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) {
if (error)
{
NSLog(#"%#", error);
}
[[NSFileManager defaultManager] removeItemAtURL:outputFileURL error:nil];
if (backgroundRecordingID != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:backgroundRecordingID];
}
}];
}
Hope can help.

Resources