Download video and save in custom album in library? - objective-c

i have created a album in my photo library using this code
NSString *albumName=#"iphonemaclover";
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library addAssetsGroupAlbumWithName:albumName
resultBlock:^(ALAssetsGroup *group) {
NSLog(#"added album:%#", albumName);
AND
I have download the video from server using this code
-(IBAction)btnDownload:(UIView *)sender {
[DSBezelActivityView newActivityViewForView:self.view withLabel:#"DOWNLOADING..."];
NSString *albumName=#"album name";
NSURL *url = [NSURL URLWithString:#"http://www.ebookfrenzy.com/ios_book/movie/movie.mov"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDownloadDestinationPath:#"/Users/seemtech/Desktop/dd/vvv.m4v"];//work fine
[ASIHTTPRequest setDefaultTimeOutSeconds:3000];
[request startAsynchronous];
}
failureBlock:^(NSError *error) {
NSLog(#"error adding album");
}];
}
-(void)requestFinished:(ASIHTTPRequest *)request
{
[[[[UIAlertView alloc] initWithTitle:#"Message"
message:#"Success!!!"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease] show]; [DSBezelActivityView removeViewAnimated:YES];
}
-(void)requestFailed:(ASIHTTPRequest *)request {
NSLog(#"error==%#",request.error); [DSBezelActivityView removeViewAnimated:YES];
}
I need to save the video in the album i created.
How can i do that?

You can save your video to your saved photos album using "ALAssetsLibrary" like this:
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSURL *capturedVideoURL = [NSURL URLWithString:#"/Users/seemtech/Desktop/dd/vvv.m4v"];
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:capturedVideoURL]) {
// request to save video in photo roll.
[library writeVideoAtPathToSavedPhotosAlbum:capturedVideoURL completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
NSLog(#"error while saving video");
} else{
[self addAssetURL:assetURL toAlbum:#"iphonemaclover"];
}
}];
}
Add that asset to your album
- (void)addAssetURL:(NSURL*)assetURL toAlbum:(NSString*)albumName
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if ([albumName compare: [group valueForProperty:ALAssetsGroupPropertyName]]==NSOrderedSame) {
//If album found
[library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
//add asset to album
[group addAsset:asset];
} failureBlock:nil];
}
else {
//if album not found create an album
[library addAssetsGroupAlbumWithName:albumName resultBlock:^(ALAssetsGroup *group) {
[self addAssetURL:assetURL toAlbum:albumName];
} failureBlock:nil];
}
} failureBlock: nil];
}
The only problem with this code is it keeps a copy of video in saved photos album. So find a way to delete an asset from albums. This Link might help.

Related

Pause/Resume download with AFNetworking 3.0 and NSURLSessionDownloadTask Objective-C, OSX

I have trouble with creating Pause/Resume download methods in my Objective-C osx app, I have tried some of the answers I found here but nothing seems to work.
Here is my code: `-(void)pauseDownload:(id)sender {
if(!downloadTask) return;
[downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
if (!resumeData) return;
[self setDownloadResumeData:resumeData];
[self setDownloadTask:nil];
}];
NSString *datastring = [[NSString alloc] initWithData:downloadResumeData encoding:NSUTF8StringEncoding];
isDownloading = NO;
NSLog(#"data %#", datastring);}`
Continue method:
-(void)continueDownload:(id)sender {
if (!self.downloadResumeData) {
return;
}
self.downloadTask = [manager.session downloadTaskWithResumeData:self.downloadResumeData];
[self.downloadTask resume];
[self setDownloadResumeData:nil];}
And download request with download task:
-(void)downloadRequest:(NSString *)url toDirectory:(NSString *)directoryName atIndex:(NSInteger) rowIndex {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSString *downloadDirectoryPath = [[NSUserDefaults standardUserDefaults] objectForKey:#"downloadPath"];
NSURL *downloadURL;
if (directoryName != nil || ![directoryName isEqualToString:#""]) {
downloadURL = [self createDownloadDirectoryIn:downloadDirectoryPath withName:directoryName];
} else {
downloadURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:#"downloadFolderPath"]];
}
downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(#"%#", downloadProgress);
// [self downloadStartedWithDownloadId:downloadID andDeviceId:userDeviceID];
isDownloading = YES;
NSNumber *downloadPercentage = [NSNumber numberWithInteger:downloadProgress.fractionCompleted *100];
progressArray[rowIndex] = downloadPercentage;
[self updateProgressBars];
} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
[[files objectAtIndex:self.tableOfContents.selectedRow] setIsFinishedDownloading:YES];
// [self downloadFinishedWithDownloadID:downloadID andDeviceID:userDeviceID];
NSLog(#"File downloaded to: %#", filePath);
}] ;
[downloadTask resume];}
Appreciate any help.

How to parse ShopStyle JSON in Objective-C

I have a snippet of some JSON which contains ShopStyle products here: https://docs.google.com/document/d/1konfjof33sgNngxIgq_sCyKmCcDda-ziXnOfUUxeKas/edit?usp=sharing
How do I go about getting the products' names and ids from the JSON? So far, I have the following code:
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"http://api.shopstyle.com/api/v2/products?pid=%#&fts=%#&offset=0&limit=50", apiKey, searchkeywords]];
NSLog(#"%#", URL);
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:URL] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
//[self.delegate fetchingGroupsFailedWithError:error];
} else {
//[self.delegate receivedGroupsJSON:data];
NSDictionary *rest_data = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSLog(#"rest_data = %#", rest_data);
for (NSDictionary *topComment in[rest_data objectForKey:#"products"]) {
[self processCommentThread:topComment andLevel:0];
}
NSLog(#"GET COMMENTS RETURN:%#", commentsContainer);
[self performSelectorOnMainThread:#selector(doneFormatting) withObject:nil waitUntilDone:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:#"%#", rest_data] delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
}
}];
/*
PSSProductQuery *productQuery = [[PSSProductQuery alloc] init];
productQuery.searchTerm = searchBar.text;
__weak typeof(self) weakSelf = self;
[[PSSClient sharedClient] searchProductsWithQuery:productQuery offset:nil limit:nil success:^(NSUInteger totalCount, NSArray *availableHistogramTypes, NSArray *products) {
weakSelf.products = products;
[resultsTableView reloadData];
NSLog(#"_products = %#", _products);
resultsTableView.hidden = NO;
} failure:^(int *operation, NSError *error) {
}];
*/
}
- (void)processCommentThread:(NSDictionary *)comments andLevel:(int)level {
#autoreleasepool {
NSMutableDictionary *comment = [[NSMutableDictionary alloc] init];
if (!([comments objectForKey:#"name"] == nil)) {
[comment setObject:[comments objectForKey:#"name"] forKey:#"name"];
}
if (!([comments objectForKey:#"id"] == nil)) {
[comment setObject:[comments objectForKey:#"id"] forKey:#"id"];
}
}
}
-(void)doneFormatting{
[myTableView reloadData];
}

iOS - Downloading Video Data from Parse

I am trying to download a PFFile which is a tfss file(?). It gets opened as a text file. This is the code I use for retrieveing the data:
-(void) queryVideoWithDictionary:(NSDictionary *)dictionary {
PFQuery *videoQuery = [PFQuery queryWithClassName:#"EventVideos"];
[videoQuery whereKey:#"objectId" equalTo:[dictionary objectForKey:#"videoId"]];
[videoQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
if (!error) {
PFFile *videoFile = [results[0] objectForKey:#"video"];
[videoFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSURL *movieURL = [NSURL fileURLWithPath:dataString];
NSMutableDictionary *videoDictionary = [NSMutableDictionary dictionaryWithObject:data forKey:[dictionary objectForKey:#"videoId"]];
[self.videoArray addObject:videoDictionary];
NSLog(#"video array count: %ld", self.videoArray.count);
NSLog(#"dataString: %#", dataString);
// NSLog(#"movieURL: %#", movieURL);
[self.player setItemByStringPath:dataString];
[self.player play];
});
}];
} else {
NSLog(#"error");
}
}];
}
When dataString gets logged, it returns null, so I don't know how to get the data and play it as a video. It is saved as a QuickTimeMovie by the way.
I use SCRecorder to play and record videos.
Edit: data is definitely not nil, I still don't know how to solve this issue.

Button press doesn't work during parsing

I cannot make back button (previous page in navigation) work during html parsing process. What I am trying to do is parsing an html and get a pdf file on viewDidAppear. During that time I want back button to be enabled because parsing can take long time. So users can decide to leave parsing process.
here is my code:
-(void)viewDidAppear:(BOOL)animated
{
[self performSelector:#selector(getPDFUrl) withObject:nil afterDelay:0];
}
-(void) getPDFUrl
{
NSURL *programURL = [NSURL URLWithString:#"http://www.example.com/somepdf/"];
NSData *programHtmlData;
#try
{
programHtmlData = [NSData dataWithContentsOfURL:programURL];
}
#catch(NSException* ex)
{}
// 2
TFHpple *programHTMLParser = [TFHpple hppleWithHTMLData:programHtmlData];
NSString *studiosXpathQueryString =
#"//div[#class='ultra_wrapper']/div[#class='container columns extra_pad boxed_lay centered']/div[#id='prk_ajax_container']/div[#id='centered_block']/div[#id='main_block']/div[#id='content']/div[#id='main']/div[#class='twelve columns sidebarized']/div[#class='prk_no_composer']/p/a";
NSArray *programNodes = [programHTMLParser searchWithXPathQuery:studiosXpathQueryString];
NSMutableArray *activities = [[NSMutableArray alloc] init];
Tutorial *tutorial;
if (programNodes.count > 0) {
for (TFHppleElement *element in programNodes)
{
#try
{
tutorial = [[Tutorial alloc] init];
tutorial.url = [element objectForKey:#"href"];
}
#catch(NSException* ex)
{
}
}
NSURL *targetURL = [NSURL URLWithString:tutorial.url];
webView.scalesPageToFit=YES;
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"warning"
message:#"warning!"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
[self performSelector:#selector(getPDFUrl) withObject:nil afterDelay:0];
will execute on main thread. Therefore Blocking your UI.
You should use
[self performSelectorInBackground:#selector(getPDFUrl) withObject:nil];
Or you can use NSOperationQueue or just NSOperation or more simple way NSBlockOperation.
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
NSLog(#"dasds");
}];
[op start];

AVAudioPlayer breaking video capture

In one of the views of my app there's a button. When pressed it is supposed to begin taking a video, trigger a sound file to start, and hide itself from view while unhiding another button. The second button is supposed to stop the video recording and make it save. Here's the code I have for the video recording, which initially worked with no problems:
in viewDidLoad:
finishButton.hidden = TRUE;
session = [[AVCaptureSession alloc] init];
movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
NSError *error;
AVCaptureDeviceInput *videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self cameraWithPosition:AVCaptureDevicePositionFront] error:&error];
if (videoInput)
{
[session addInput:videoInput];
}
AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
NSError *audioError = nil;
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioCaptureDevice error:&audioError];
if (audioInput)
{
[session addInput:audioInput];
}
Float64 TotalSeconds = 35; //Total seconds
int32_t preferredTimeScale = 30; //Frames per second
CMTime maxDuration = CMTimeMakeWithSeconds(TotalSeconds, preferredTimeScale);
movieFileOutput.maxRecordedDuration = maxDuration;
movieFileOutput.minFreeDiskSpaceLimit = 1024 * 1024;
if ([session canAddOutput:movieFileOutput])
[session addOutput:movieFileOutput];
[session setSessionPreset:AVCaptureSessionPresetMedium];
if ([session canSetSessionPreset:AVCaptureSessionPreset640x480]) //Check size based configs are supported before setting them
[session setSessionPreset:AVCaptureSessionPreset640x480];
[self cameraSetOutputProperties];
[session startRunning];
and for the button:
-(IBAction)start:(id)sender
{
startButton.hidden = TRUE;
finishButton.hidden = FALSE;
//Create temporary URL to record to
NSString *outputPath = [[NSString alloc] initWithFormat:#"%#%#", NSTemporaryDirectory(), #"output.mov"];
self.outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:outputPath])
{
NSError *error;
if ([fileManager removeItemAtPath:outputPath error:&error] == NO)
{
//Error - handle if required
}
}
//Start recording
[movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];
finally, under the last button:
[movieFileOutput stopRecording];
and here's the code to save the video:
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error
{
NSLog(#"didFinishRecordingToOutputFileAtURL - enter");
BOOL RecordedSuccessfully = YES;
if ([error code] != noErr)
{
// A problem occurred: Find out if the recording was successful.
id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
if (value)
{
RecordedSuccessfully = [value boolValue];
}
}
if (RecordedSuccessfully)
{
//----- RECORDED SUCESSFULLY -----
NSLog(#"didFinishRecordingToOutputFileAtURL - success");
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:outputURL])
{
[library writeVideoAtPathToSavedPhotosAlbum:outputURL
completionBlock:^(NSURL *assetURL, NSError *error)
{
if (error)
{
}
}];
}
}
}
All of this was working just fine. Then I added a few lines so that a song file would play when the start button was pressed.
in viewDidLoad:
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/Song.aiff", [[NSBundle mainBundle] resourcePath]]];
NSError *audioFileError;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&audioFileError];
player.numberOfLoops = 0;
[self.player prepareToPlay];
and under the start button:
if (player == nil)
NSLog(#"Audio file could not be played");
else
[player play];
Now when the start button is pressed the song plays with no problems, but the video capture is messed up. Before adding the AVAudioPlayer stuff I would get the "didFinishRecordingToOutputFileAtURL - enter" and "didFinishRecordingToOutputFileAtURL - success" logs when I pressed the finish button, and now I get the first log as soon as I press the start button, nothing happens when I press the finish button, and no video is recorded. If I comment out the lines that make the song play then the video capture works just fine again. Any ideas what's going on here?
- (void)setupAudioSession
{
static BOOL audioSessionSetup = NO;
if (audioSessionSetup)
{
return;
}
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doSetProperty), &doSetProperty);
[[AVAudioSession sharedInstance] setActive: YES error: nil];
audioSessionSetup = YES;
}
- (void)playAudio
{
[self setupAudioSession];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"btnClick" ofType:#"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[fileURL release];
self.audioPlayer = newPlayer;
[newPlayer release];
[audioPlayer setDelegate:self];
[audioPlayer prepareToPlay];
audioPlayer.volume=1.0;
[audioPlayer play];
}
NOTE: Add the framework: AudioToolbox.framework.
#import <AudioToolbox/AudioServices.h>