Messages Extension Send Audio File - ios10

I have this URL
myString =
file:///var/mobile/Containers/Data/PluginKitPlugin/-------/Documents/MyAudio.m4a
and here is my send code
MSConversation * conversation = self.activeConversation;
if (conversation) {
MSMessageTemplateLayout * activeLayout = [[MSMessageTemplateLayout alloc] init];
// activeLayout.image = image;
activeLayout.caption = #"Message Counter";
activeLayout.subcaption = #"Message subcaption";
activeLayout.trailingCaption = #"Trailing caption";
activeLayout.trailingSubcaption = #"Trailing Subcaption";
activeLayout.mediaFileURL = [NSURL URLWithString:myString];
activeLayout.imageTitle = #"Image counter";
activeLayout.imageSubtitle = #"Image subtitle";
MSMessage * message = [[MSMessage alloc] init];
message.layout = activeLayout;
message.URL = [NSURL URLWithString:#"Empty URL"];
message.summaryText = #"This is Summary";
[conversation insertMessage:message completionHandler:^(NSError *error) {
if (error) {
NSLog(#"Error sending message %#", [error localizedDescription]);
}
}];
}
else {
NSLog(#"No &%#%&^# conversation found");
}
i can't get the audio file for sending i have just Message Counter and etc..

Instead of using insertMessage use insertAttachment-
[[conversation insertAttachment:[NSURL URLWithString:myString]; withAlternateFilename:#"Alternate Name" completionHandler:^(NSError * error) {
DDLogInfo(#"Error is %#",error);
}];

Related

Recording video with AVCaptureSession

I'm trying to record a video using AVCaptureSession and AVCaptureMovieFileOutput but whenever I try to start recording I get this error in the didFinishRecordingToOutputFileAtURL AVCaptureFileOutputRecordingDelegate method.
Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo=0x15de7c40 {AVErrorRecordingSuccessfullyFinishedKey=false, NSLocalizedDescription=The operation could not be completed, NSLocalizedFailureReason=An unknown error occurred (-12673), NSUnderlyingError=0x15d88aa0 "The operation couldn’t be completed. (OSStatus error -12673.)"}
This is the code I'm using to add the AVCaptureMovieFileOutput and initialise my AVCaptureSession
- (AVCaptureSession *)session {
if (!_session) {
_session = [[AVCaptureSession alloc] init];
// ADD CAMERA DEVICE
NSError *error = nil;
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:self.videoDevice error:&error];
if (!videoInput) {
NSLog(#"ERROR: trying to open camera: %#", error);
} else {
[_session addInput:videoInput];
}
// ADD AUDIO DEVICE
error = nil;
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:self.audioDevice error:&error];
if (!audioInput)
{
NSLog(#"ERROR: trying to open mic: %#", error);
} else {
[_session addInput:audioInput];
}
// ADD OUTPUT FILE
if ([_session canAddOutput:self.movieFileOutput]) {
[_session addOutput:self.movieFileOutput];
}
[_session startRunning];
}
return _session;
}
My AVCaptureMovieFileOutput is lazy loaded like this
- (AVCaptureMovieFileOutput *)movieFileOutput {
if (!_movieFileOutput) {
_movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
Float64 TotalSeconds = 60; //Total seconds
int32_t preferredTimeScale = 30; //Frames per second
CMTime maxDuration = CMTimeMakeWithSeconds(TotalSeconds, preferredTimeScale);
_movieFileOutput.maxRecordedDuration = maxDuration;
_movieFileOutput.minFreeDiskSpaceLimit = 1024 * 1024;
}
return _movieFileOutput;
}
I'm not sure what I'm doing wrong as most of the tutorials I've seen do it this way.
Thanks
Underlying error code is -12673, which is usually caused by attempt to write into unwritable directory or file. Try to write using this code:
NSString *documentsDirPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSURL *documentsDirUrl = [NSURL fileURLWithPath:documentsDirPath isDirectory:YES];
NSURL *url = [NSURL URLWithString:#"out.mp4" relativeToURL:documentsDirUrl];
[self.movieFileOutput startRecordingToOutputFileURL:url recordingDelegate:self];

Listing All Folder content from Google Drive

Hi I have integrated google Dive with my app using Dr. Edit sample code from google drive. But i am not able to view all the files, which are stored in my Google Drive account.
// I have tried this
-(void)getFileListFromSpecifiedParentFolder
{
GTLQueryDrive *query2 = [GTLQueryDrive queryForChildrenListWithFolderId:#"root"];
query2.maxResults = 1000;
[self.driveService executeQuery:query2
completionHandler:^(GTLServiceTicket *ticket,
GTLDriveChildList *children, NSError *error)
{
NSLog(#"\nGoogle Drive: file count in the folder: %d", children.items.count);
if (!children.items.count)
{
return ;
}
if (error == nil)
{
for (GTLDriveChildReference *child in children)
{
GTLQuery *query = [GTLQueryDrive queryForFilesGetWithFileId:child.identifier];
[self.driveService executeQuery:query completionHandler:^(GTLServiceTicket *ticket,
GTLDriveFile *file,
NSError *error)
{
NSLog(#"\nfile name = %#", file.originalFilename);}];
}
}
}];
}
//I want to Display All content in NSLog...
1. How to get all files from Google Drive.
First in viewDidLoad: method check for authentication
-(void)viewDidLoad
{
[self checkForAuthorization];
}
And here is the definition of all methods:
// This method will check the user authentication
// If he is not logged in then it will go in else condition and will present a login viewController
-(void)checkForAuthorization
{
// Check for authorization.
GTMOAuth2Authentication *auth =
[GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
clientID:kClientId
clientSecret:kClientSecret];
if ([auth canAuthorize])
{
[self isAuthorizedWithAuthentication:auth];
}
else
{
SEL finishedSelector = #selector(viewController:finishedWithAuth:error:);
GTMOAuth2ViewControllerTouch *authViewController =
[[GTMOAuth2ViewControllerTouch alloc] initWithScope:kGTLAuthScopeDrive
clientID:kClientId
clientSecret:kClientSecret
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:finishedSelector];
[self presentViewController:authViewController animated:YES completion:nil];
}
}
// This method will be call after logged in
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController finishedWithAuth: (GTMOAuth2Authentication *)auth error:(NSError *)error
{
[self dismissViewControllerAnimated:YES completion:nil];
if (error == nil)
{
[self isAuthorizedWithAuthentication:auth];
}
}
// If everthing is fine then initialize driveServices with auth
- (void)isAuthorizedWithAuthentication:(GTMOAuth2Authentication *)auth
{
[[self driveService] setAuthorizer:auth];
// and finally here you can load all files
[self loadDriveFiles];
}
- (GTLServiceDrive *)driveService
{
static GTLServiceDrive *service = nil;
if (!service)
{
service = [[GTLServiceDrive alloc] init];
// Have the service object set tickets to fetch consecutive pages
// of the feed so we do not need to manually fetch them.
service.shouldFetchNextPages = YES;
// Have the service object set tickets to retry temporary error conditions
// automatically.
service.retryEnabled = YES;
}
return service;
}
// Method for loading all files from Google Drive
-(void)loadDriveFiles
{
GTLQueryDrive *query = [GTLQueryDrive queryForFilesList];
query.q = [NSString stringWithFormat:#"'%#' IN parents", #"root"];
// root is for root folder replace it with folder identifier in case to fetch any specific folder
[self.driveService executeQuery:query completionHandler:^(GTLServiceTicket *ticket,
GTLDriveFileList *files,
NSError *error) {
if (error == nil)
{
driveFiles = [[NSMutableArray alloc] init];
[driveFiles addObjectsFromArray:files.items];
// Now you have all files of root folder
for (GTLDriveFile *file in driveFiles)
NSLog(#"File is %#", file.title);
}
else
{
NSLog(#"An error occurred: %#", error);
}
}];
}
Note: For get full drive access your scope should be kGTLAuthScopeDrive.
[[GTMOAuth2ViewControllerTouch alloc] initWithScope:kGTLAuthScopeDrive
clientID:kClientId
clientSecret:kClientSecret
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:finishedSelector];
2. How to download a specific file.
So for this you will have to use GTMHTTPFetcher. First get the download URL for that file.
NSString *downloadedString = file.downloadUrl; // file is GTLDriveFile
GTMHTTPFetcher *fetcher = [self.driveService.fetcherService fetcherWithURLString:downloadedString];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error)
{
if (error == nil)
{
if(data != nil){
// You have successfully downloaded the file write it with its name
// NSString *name = file.title;
}
}
else
{
NSLog(#"Error - %#", error.description)
}
}];
Note: If you found "downloadedString" null Or empty just have look at file.JSON there are array of "exportsLinks" then you can get the file with one of them.
3. How to upload a file in specific folder: This is an example of uploading image.
-(void)uploadImage:(UIImage *)image
{
// We need data to upload it so convert it into data
// If you are getting your file from any path then use "dataWithContentsOfFile:" method
NSData *data = UIImagePNGRepresentation(image);
// define the mimeType
NSString *mimeType = #"image/png";
// This is just because of unique name you can give it whatever you want
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd-MMM-yyyy-hh-mm-ss"];
NSString *fileName = [df stringFromDate:[NSDate date]];
fileName = [fileName stringByAppendingPathExtension:#"png"];
// Initialize newFile like this
GTLDriveFile *newFile = [[GTLDriveFile alloc] init];
newFile.mimeType = mimeType;
newFile.originalFilename = fileName;
newFile.title = fileName;
// Query and UploadParameters
GTLUploadParameters *uploadParameters = [GTLUploadParameters uploadParametersWithData:data MIMEType:mimeType];
GTLQueryDrive *query = [GTLQueryDrive queryForFilesInsertWithObject:newFile uploadParameters:uploadParameters];
// This is for uploading into specific folder, I set it "root" for root folder.
// You can give any "folderIdentifier" to upload in that folder
GTLDriveParentReference *parentReference = [GTLDriveParentReference object];
parentReference.identifier = #"root";
newFile.parents = #[parentReference];
// And at last this is the method to upload the file
[[self driveService] executeQuery:query completionHandler:^(GTLServiceTicket *ticket, id object, NSError *error) {
if (error){
NSLog(#"Error: %#", error.description);
}
else{
NSLog(#"File has been uploaded successfully in root folder.");
}
}];
}

Javascript Youtube API: buffering for ever - UIWebView iOS

I am using the YouTube API in UIWebView.
I have created a NSString with the HTML5 player that I load in the UIWebView. Everything works perfectly on iPhone 5 and iPad.
But, if I test the app using an iPhone 4, the player returns the buffering state all the time. Only if I explicitly press the play button, the player starts playing, without stopping again for buffering. It seems that although the video has been buffered, the player still gives me this state.
Is anyone aware of this problem? Any idea?
Thank you very much in advance!!
In LBYouTubePlayerViewController.m file
Replace Following method on yr old Method....
then test...
-(NSURL*)_extractYouTubeURLFromFile:(NSString *)html error:(NSError *__autoreleasing *)error {
NSString *JSONStart = nil;
// NSString *JSONStartFull = #"ls.setItem('PIGGYBACK_DATA', \")]}'";
NSString *JSONStartFull = #"bootstrap_data = \")]}'";
NSString *JSONStartShrunk = [JSONStartFull stringByReplacingOccurrencesOfString:#" " withString:#""];
if ([html rangeOfString:JSONStartFull].location != NSNotFound)
JSONStart = JSONStartFull;
else if ([html rangeOfString:JSONStartShrunk].location != NSNotFound)
JSONStart = JSONStartShrunk;
if (JSONStart != nil) {
NSScanner* scanner = [NSScanner scannerWithString:html];
[scanner scanUpToString:JSONStart intoString:nil];
[scanner scanString:JSONStart intoString:nil];
NSString *JSON = nil;
[scanner scanUpToString:#"}\";" intoString:&JSON];
JSON = [NSString stringWithFormat:#"%#}",JSON]; // Add closing bracket } to get vallid JSON again
// [scanner scanUpToString:#"\");" intoString:&JSON];
JSON = [self _unescapeString:JSON];
NSError* decodingError = nil;
NSDictionary* JSONCode = nil;
// First try to invoke NSJSONSerialization (Thanks Mattt Thompson)
id NSJSONSerializationClass = NSClassFromString(#"NSJSONSerialization");
SEL NSJSONSerializationSelector = NSSelectorFromString(#"dataWithJSONObject:options:error:");
if (NSJSONSerializationClass && [NSJSONSerializationClass respondsToSelector:NSJSONSerializationSelector]) {
JSONCode = [NSJSONSerialization JSONObjectWithData:[JSON dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&decodingError];
}
else {
JSONCode = [JSON objectFromJSONStringWithParseOptions:JKParseOptionNone error:&decodingError];
}
if (decodingError) {
// Failed
*error = decodingError;
}
else {
// Success
NSDictionary *dict = [JSONCode objectForKey:#"content"];
NSDictionary *dictTemp = [dict objectForKey:#"video"];
NSArray* videos = [dictTemp objectForKey:#"fmt_stream_map"];
NSString* streamURL = nil;
if (videos.count) {
NSString* streamURLKey = #"url";
if (self.quality == LBYouTubePlayerQualityLarge) {
streamURL = [[videos objectAtIndex:0] objectForKey:streamURLKey];
}
else if (self.quality == LBYouTubePlayerQualityMedium) {
unsigned int index = MAX(0, videos.count-2);
streamURL = [[videos objectAtIndex:index] objectForKey:streamURLKey];
}
else {
streamURL = [[videos lastObject] objectForKey:streamURLKey];
}
}
if (streamURL) {
return [NSURL URLWithString:streamURL];
}
else {
*error = [NSError errorWithDomain:kLBYouTubePlayerControllerErrorDomain code:2 userInfo:[NSDictionary dictionaryWithObject:#"Couldn't find the stream URL." forKey:NSLocalizedDescriptionKey]];
}
}
}
else {
*error = [NSError errorWithDomain:kLBYouTubePlayerControllerErrorDomain code:3 userInfo:[NSDictionary dictionaryWithObject:#"The JSON data could not be found." forKey:NSLocalizedDescriptionKey]];
}
return nil;
}

How to overcome from the error " The requested URL was not found on this server "in AVfoundation

I am working on video app.I have to capture and trim the video.I had done this using AVFoundation framework.When I am calling trim method I am getting error " The requested URL was not found on this server".
I used the following code to trim and play the video
- (IBAction)showTrimmedVideo:(UIButton *)sender
{
[self deleteTmpFile];
NSURL *videoFileUrl = [NSURL fileURLWithPath:originalVideoPath];
NSLog(#"Video to trim is %#",videoFileUrl);
AVAsset *anAsset = [[AVURLAsset alloc] initWithURL:videoFileUrl options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:anAsset];
if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality])
{
self.exportSession = [[AVAssetExportSession alloc]
initWithAsset:anAsset presetName:AVAssetExportPresetPassthrough];
// Implementation continues.
NSURL *furl = [NSURL fileURLWithPath:originalVideoPath];
NSLog(#"Original file path is %#",furl);
self.exportSession.outputURL = furl;
self.exportSession.outputFileType = AVFileTypeQuickTimeMovie;
CMTime start = CMTimeMakeWithSeconds(self.startTime, anAsset.duration.timescale);
CMTime duration = CMTimeMakeWithSeconds(self.stopTime-self.startTime, anAsset.duration.timescale);
CMTimeRange range = CMTimeRangeMake(start, duration);
self.exportSession.timeRange = range;
self.trimBtn.hidden = YES;
self.myActivityIndicator.hidden = NO;
[self.myActivityIndicator startAnimating];
[self.exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([self.exportSession status])
{
case AVAssetExportSessionStatusFailed:
NSLog(#"Export failed: %#", [[self.exportSession error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(#"Export canceled");
break;
default:
NSLog(#"NONE");
dispatch_async(dispatch_get_main_queue(), ^{
[self.myActivityIndicator stopAnimating];
self.myActivityIndicator.hidden = YES;
self.trimBtn.hidden = NO;
[self playMovie:self.tmpVideoPath];
});
break;
}
}];
}
}
-(void)deleteTmpFile
{
NSURL *url = [NSURL fileURLWithPath:originalVideoPath];
NSFileManager *fm = [NSFileManager defaultManager];
BOOL exist = [fm fileExistsAtPath:url.path];
NSError *err;
if (exist) {
[fm removeItemAtURL:url error:&err];
NSLog(#"file deleted");
if (err)
{
NSLog(#"file remove error, %#", err.localizedDescription );
}
} else {
NSLog(#"no file by that name");
}
}
Every time its going into " AVAssetExportSessionStatusFailed:" case and showing above error.
I am not getting where I had gone wrong.Please suggest me what to do now.
you problem here is, you are first deleting the file and trying to use it with export session. You should not delete the file while export is in progress, and I recommend you to save exported file to temporary directory, after export is done, just delete your old file and move the exported one to the original file URL. Good Luck!

Twitter search for hashtag

I'm trying to parse tweets using Twitter Framework, so I write the following code and it's working fine, but it's not Synchronous.
Now I'm trying to get all the tweets from #iOS.
I have used the following code to get the search result for iOS hashtag:
-(void)fetchResults
{
// Do a simple search, using the Twitter API
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
#"http://search.twitter.com/search.json?q=iOS%20&rpp=20&with_twitter_user_id=true&result_type=recent"]
parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(#"Twitter response: %#", [dict description]);
[self filterTweets];
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
As a result I got this:
Twitter response: {
"completed_in" = "0.007";
"max_id" = 333837474914766848;
"max_id_str" = 333837474914766848;
page = 1;
query = quranRadios;
"refresh_url" = "?since_id=333837474914766848&q=quranRadios&result_type=recent";
results = (
{
"created_at" = "Mon, 13 May 2013 06:53:51 +0000";
"from_user" = YousefMutawe;
"from_user_id" = 324385406;
"from_user_id_str" = 324385406;
"from_user_name" = "Yousef N Mutawe \Uf8ff";
geo = "<null>";
id = 333837474914766848;
"id_str" = 333837474914766848;
"iso_language_code" = pt;
metadata = {
"result_type" = recent;
};
"profile_image_url" = "http://a0.twimg.com/profile_images/1533729607/20090719526_normal.jpg";
"profile_image_url_https" = "https://si0.twimg.com/profile_images/1533729607/20090719526_normal.jpg";
source = "<a href="http://twitter.com/download/iphone">Twitter for iPhone</a>";
text = "Testing #quranRadios #Mkalatrash";
},
{
"created_at" = "Sun, 12 May 2013 13:09:43 +0000";
"from_user" = YousefMutawe;
"from_user_id" = 324385406;
"from_user_id_str" = 324385406;
"from_user_name" = "Yousef N Mutawe \Uf8ff";
geo = "<null>";
id = 333569679484416000;
"id_str" = 333569679484416000;
"iso_language_code" = et;
metadata = {
"result_type" = recent;
};
"profile_image_url" = "http://a0.twimg.com/profile_images/1533729607/20090719526_normal.jpg";
"profile_image_url_https" = "https://si0.twimg.com/profile_images/1533729607/20090719526_normal.jpg";
source = "<a href="http://twitter.com/download/iphone">Twitter for iPhone</a>";
text = "#quranRadios :)";
}
);
"results_per_page" = 20;
"since_id" = 0;
"since_id_str" = 0;
}
So i use the following method to filter the result and to get the (Tweet,Username,and the User image):
-(void)filterTweets
{
NSArray *results = [dict objectForKey:#"results"];
//Loop through the results
int x =0;
for (NSDictionary *tweet in results)
{
// Get the tweet
NSString *twittext = [tweet objectForKey:#"text"];
NSString *twitPic = [tweet objectForKey:#"profile_image_url"];
NSString *userName = [tweet objectForKey:#"from_user"];
// Save the tweet to the twitterText array
[tweetsInfo addObject:(twittext)];
[tweetPics addObject:(twitPic)];
[imagesArray addObject:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[tweetPics objectAtIndex:x]]]]];
[userNameTweet addObject:userName];
x++;
//NSLog(#"tweet ooooooo ======> %#",twitPic);
countMe++;
}
[tweetsTable reloadData];
}
I'm not sure if i'm doing the right thing,so what would you recommend me to do? and how can i make it synchronized?
am new to programming iOS, please advice.
Thanks.