How to get a video PHAsset disk file size? - avasset

I'm trying to determine the file size on disk of a PHAsset video.
The following code is returning am error "The file “IMG_0188.mov” couldn’t be opened because you don’t have permission to view it."
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
videoURL = [(AVURLAsset*)avAsset URL];
NSNumber *videoDiskFileSize;
NSError *error;
[videoURL getResourceValue:&videoDiskFileSize forKey:NSURLFileSizeKey error:&error];
if(error){
NSLog(#"ERROR %#", error.localizedDescription);
}
NSLog(#"size is %f",[videoDiskFileSize floatValue]/(1024.0*1024.0));
}];

Here's the correct way to do it.
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestExportSessionForVideo:asset options:options exportPreset:AVAssetExportPresetHighestQuality resultHandler:^(AVAssetExportSession *exportSession, NSDictionary *info) {
CMTime videoDuration = CMTimeMultiplyByFloat64(exportSession.asset.duration, 1);
exportSession.timeRange = CMTimeRangeMake(kCMTimeZero, videoDuration);
NSLog(#"Byyte size = %lld", exportSession.estimatedOutputFileLength);
videoSize = exportSession.estimatedOutputFileLength;
}];

Related

Posting user profile pic to twitter giving Error 131

When trying to post a users profile pic to twitter, I am getting Error code 131 response back:
2013-12-06 19:17:29.854 Tweetly[8131:60b] {
errors = (
{
code = 131;
message = "Internal error";
}
);
}
Twitters website lists this:
"Corresponds with an HTTP 500 - An unknown internal error occurred."
Here is my code:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//Code for store image
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
UIImage *scaledImage = [self imageWithImage:image convertToSize:CGSizeMake(500, 500)];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(scaledImage)];
[self uploadPictureWithData:imageData];
}
- (UIImage *)imageWithImage:(UIImage *)image convertToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return destImage;
}
- (void)uploadPictureWithData:(NSData *)imageData {
// Get the twitter feed
NSURL *requestURL = [NSURL URLWithString:#"https://api.twitter.com/1.1/account/update_profile_image.json"];
// Set up proper parameters
NSMutableDictionary *timelineParameters = [[NSMutableDictionary alloc] init];
[timelineParameters setObject:imageData forKey:#"image"];
[timelineParameters setObject:#"1" forKey:#"skip_status"];
// Create the Social Request
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:requestURL parameters:timelineParameters];
postRequest.account = self.delegate.userAccount;
// Perform the request
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
// Check if we reached the reate limit
if ([urlResponse statusCode] == 429) {
// Rate limit reached
// Display an alert letting the user know we have hit the rate limit
UIAlertView *twitterAlert = [[UIAlertView alloc] initWithTitle:kRateLimitTitle
message:kRateLimitMessage
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[twitterAlert show];
return;
}
// Check if there was an error
if (error) {
NSLog(#"Error: %#", error.localizedDescription);
return;
}
// Check if there is some response data
if (responseData) {
NSError *jsonError = nil;
NSMutableArray *feedData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonError];
if (!jsonError) {
// Check the response data
NSLog(#"%#", feedData);
} else {
// Alert the user with the error
UIAlertView *twitterAlert = [[UIAlertView alloc] initWithTitle:kErrorTitle
message:kErrorMessage
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[twitterAlert show];
}
} else {
// Alert the user with the error
UIAlertView *twitterAlert = [[UIAlertView alloc] initWithTitle:kErrorTitle
message:kErrorMessage
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[twitterAlert show];
}
});
}];
}
Any idea what the issue might be? I initially thought it was because the image was too big, so I added the method for scaling the image down to 500 x 500, but I get the same error.
This error happens while running on both the device and the simulator.
Does anyone see where the problem is or have any extra insight? Thanks!
In my tests, images larger than 1000x1000px are not downscaled synchronously, throwing the 131 response code. Undocumented, unfortunately.
Make sure the image is <700kb and smaller than 1000x1000px.
https://dev.twitter.com/rest/reference/post/account/update_profile_image

Audio playing not working when ios device is locked

I am doing the following things to make audio play when an iOS device is locked, but it doesn't work.
UIBackgroundModes key (with the value audio) in Info.plist file.
set up audio session
code:
- (void)viewDidLoad
{
[super viewDidLoad];
[self createAudioSession];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"jgj" ofType:#"mp3"];
NSURL *url = [NSURL fileURLWithPath:soundFilePath];
NSLog(#"%#",[url path]);
NSError* error;
self.audioPlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (self.audioPlayer == nil)
NSLog(#"%#",[error description]);
else
{
self.audioPlayer.numberOfLoops=-1;
[self.audioPlayer play];
}
}
-(void)createAudioSession
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
// Use this code to allow the app sound to continue to play when the screen is locked.
NSError* error=nil;
BOOL ok=[audioSession setCategory: AVAudioSessionCategoryPlayback error: &error];
if(!ok)
NSLog(#"%#",[error description]);
else
NSLog(#"hello");
ok=[audioSession setActive:YES error:&error];
if(!ok)
NSLog(#"%#",[error description]);
else
NSLog(#"world");
}

GPUImageView Integration in my project

What I am trying to do is this.
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url2 = [[NSBundle mainBundle] URLForResource:#"NAN" withExtension:#"mov"];
GPUImageMovie *movie2 = [[GPUImageMovie alloc] initWithURL:url2];
movie2.playAtActualSpeed = YES;
filter0 = [[GPUImageSepiaFilter alloc] init];
[movie2 addTarget:filter0];
[filter0 addTarget:view0]; // view0 is a GPUImageView taken in nib
[self recordVideo];
isRecording = YES;
[movie2 startProcessing];
[movieWriter setCompletionBlock:^{
if (isRecording) {
[self stopRecording];
isRecording = NO;
} }];
}
-(void)recordVideo {
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:#"file.mov"];
NSURL *url = [NSURL fileURLWithPath:path];
NSFileManager *fm = [NSFileManager defaultManager];
[fm removeItemAtPath:path error:nil];
movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:url size:CGSizeMake(640, 480)];
[filter0 addTarget:movieWriter];
[movieWriter startRecording];
}
-(void)stopRecording {
[movieWriter finishRecording];
}
But this is not working at all. I always get a black video with this code. There is no crash, I get a black video with the same duration as of original video. Has anyone faced the same issue. Kindly help.
Any help would be great.

Get text file from document directory ipad

All,In my requirement need to send a mail with attached text file, which is in document directory,Here i can get the path of file which is in document directory,How do i attach the file from my ipad to send.
here is the code which i have tried
MFMailComposeViewController *picker=[[MFMailComposeViewController alloc]init];
picker.mailComposeDelegate=self;
if ([MFMailComposeViewController canSendMail]){
// Create and show composer
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSLog(#"directry path %#",paths);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:#"Logs/log-858743.txt"];
NSLog(#"directry full path %#",fullPath);
NSData *data = [NSData dataWithContentsOfFile: fullPath];
NSLog(#"Data value %#",data);
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fullPath];
if (fileExists) {
NSLog(#"file is there");
}else{
NSLog(#"file is not there");
}
[picker setSubject:#"Backup"];
[picker addAttachmentData:data mimeType:#"text/rtf" fileName:#"log.txt"];
[picker setMessageBody:#"testing." isHTML:NO];
[self presentModalViewController:picker animated:YES];
[picker release]; }
else{
// Show some error message here
}
Here a sample, try this
MFMailComposeViewController *mViewController = [[MFMailComposeViewController alloc] init];
mViewController.mailComposeDelegate = self;
//Imposto l'oggetto
[mViewController setSubject:#"Invio Copia Commissione"];
//Preparo l' A: Devo spezzare gli indirizzi E-mail
NSArray *toRecipients = [NSArray arrayWithArray:[Globals.AEmail componentsSeparatedByString:#";"]];
[mViewController setToRecipients:toRecipients];
//Preparo il Cc: Devo spezzare gli indirizzi E-mail
if ([Config.EmailAgg length] != 0) {
NSArray *CcRecipients = [NSArray arrayWithArray:[Config.EmailAgg componentsSeparatedByString:#";"]];
[mViewController setCcRecipients:CcRecipients];
}
//Setto il corpo dell'E-mail
[mViewController setMessageBody:Globals.TestoEmail isHTML:NO];
//A questo punto visto che ho fatto 30 salvo il testo anche come file allegato dell'E-mail
[Globals.TestoEmail writeToFile:[NSString stringWithFormat:#"%#/CopiaCommissione.txt", Globals.DocumentsPath] atomically:TRUE encoding:NSUTF8StringEncoding error:nil];
NSData *Allegato = [NSData dataWithContentsOfFile:[NSString stringWithFormat:#"%#/CopiaCommissione.txt", Globals.DocumentsPath]];
[mViewController addAttachmentData:Allegato mimeType:#"text/plain" fileName:#"CopiaCommissione.txt"];
[self presentModalViewController:mViewController animated:YES];
[mViewController release];
try to change mimeType in your code like this
[picker addAttachmentData:data mimeType:#"text/plain" fileName:#"log.txt"];

i had some images in resultstring i want to display it in tableview

i had some images in resultstring ,resultstring is what i get from the server ,it contains images ,i want that images and display it in tableview
my code is
viewdidload
{
NSString *urlVal = #"http://at.azinova.info/green4care/iphone/viewImage.php?id=";
NSString *urlVal1 = [urlVal stringByAppendingString:selectedCountryw];
NSURL *url1 = [NSURL URLWithString:urlVal1];
//NSURL *url1 = [NSURL URLWithString:urlVal];
NSString *resultString = [NSString stringWithContentsOfURL:url1 encoding:NSUTF8StringEncoding error:nil];
NSArray *arycountries1 = [resultString componentsSeparatedByString:#","];
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Message" message:resultString delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
//arraycountries = [[NSArray alloc]initWitho:arycountries1];
arraycountries = [[NSArray alloc]initWithArray: arycountries1];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [arraycountries count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.imageView.image = [UIImage imageNamed:[arraycountries objectAtIndex:indexPath.row]];
// Configure the cell...
return cell;
}
please help
thankzzzzz
What you described is much like a message borad with images, there is a twitter open source project tweetero: http://code.google.com/p/tweetero/ You can take a look at MessageListController and ImageLoader.
In generally, you could do like this:
1) Send async request to server to get message date(not images)
2) reload the table data, and send the image loader request for each uiimageview.
3) set the uiimageview when the image is loaded. A default loading image can be used until the real image is loaded.

Resources