I want to upload video from my app to the youtube. I am using the example YoutubeTest for this purpose. I have set the developer key and client Id for my app. Now when trying to upload the video using example source code, it shows an error which is:
2012-03-19 10:51:07.947 YouTubeTest[539:f803] serviceBase: objectFetcher: failedWithStatus:400 data:
2012-03-19 10:51:07.985 YouTubeTest[539:f803] Error: Error Domain=com.google.GDataServiceDomain Code=400 "The operation couldn’t be completed. (com.google.GDataServiceDomain error 400.)" UserInfo=0x6c49e50 {}
Has anyone successfully implemented the GData to upload videos to youtube from the iphone app. Can anyone give me the example source code.
Yes ofcourse many had successfully implemented it ... hmmm try this link http://urinieto.com/category/google/ follow instructions line by line.
Not Sure y you are getting this error. Follow above instructions if problem still persists i will help you out .
Cheers
I am having the same issue with YouTubeTest app. here is the code for request:
(IBAction)uploadPressed:(id)sender {
NSString *devKey = [mDeveloperKeyField text];
GDataServiceGoogleYouTube *service = [self youTubeService];
[service setYouTubeDeveloperKey:devKey];
NSString *username = [mUsernameField text];
NSString *clientID = [mClientIDField text];
NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:username
clientID:clientID];
// load the file data
NSString *path = [[NSBundle mainBundle] pathForResource:#"YouTubeTest" ofType:#"m4v"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSString *filename = [path lastPathComponent];
// gather all the metadata needed for the mediaGroup
NSString *titleStr = [mTitleField text];
GDataMediaTitle *title = [GDataMediaTitle textConstructWithString:titleStr];
NSString *categoryStr = [mCategoryField text];
GDataMediaCategory *category = [GDataMediaCategory mediaCategoryWithString:categoryStr];
[category setScheme:kGDataSchemeYouTubeCategory];
NSString *descStr = [mDescriptionField text];
GDataMediaDescription *desc = [GDataMediaDescription textConstructWithString:descStr];
NSString *keywordsStr = [mKeywordsField text];
GDataMediaKeywords *keywords = [GDataMediaKeywords keywordsWithString:keywordsStr];
BOOL isPrivate = mIsPrivate;
GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
[mediaGroup setMediaTitle:title];
[mediaGroup setMediaDescription:desc];
[mediaGroup addMediaCategory:category];
[mediaGroup setMediaKeywords:keywords];
[mediaGroup setIsPrivate:isPrivate];
NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:path
defaultMIMEType:#"video/mp4"];
// create the upload entry with the mediaGroup and the file data
GDataEntryYouTubeUpload *entry;
entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
data:data
MIMEType:mimeType
slug:filename];
SEL progressSel = #selector(ticket:hasDeliveredByteCount:ofTotalByteCount:);
[service setServiceUploadProgressSelector:progressSel];
GDataServiceTicket *ticket;
ticket = [service fetchEntryByInsertingEntry:entry
forFeedURL:url
delegate:self
didFinishSelector:#selector(uploadTicket:finishedWithEntry:error:)];
[self setUploadTicket:ticket];
}
Solved my problem. The error info in your case is not enough. But if you print out the HTTPURLResponse from the server , it will help to spot the error. In my case keywords length was too long.
I faced the same error. But I did find a solution through trial and error :)
Actually as Youtube itself states
You don't need to provide Client_Id anymore. Please remove it.
But the actual problem was with the login credentials. API was returning error response when i login as "xyz#gmail.com". It started working when i provided just the username without domain "xyz".
Hope this helps!
Related
This is my code which is not working for any mp3 files:
//define AVassets
NSURL *assetUrl2 = [[NSURL fileURLWithPath:
[assetLoc stringByAppendingPathComponent:title]]
URLByAppendingPathExtension:ext]
AVAsset *asset2 = [AVURLAsset URLAssetWithURL:assetUrl2
options:nil];
//print asset url
NSString *encodedString = [assetUrl2 absoluteString];
NSLog(#"song name%#",encodedString); //this prints the valid url
NSArray *origMetadata =
[asset2 metadataForFormat:AVMetadataFormatID3Metadata];
for (AVMetadataItem *item in origMetadata) {
NSLog(#"*** ID3 tags found");
NSString *keys = (NSString *)[item key];
NSString *value = [item stringValue];
NSLog(#"value for tag:%# is:%#", keys, value);
}
However, if I swap...
`NSArray *origMetadata =
[asset2 metadataForFormat:AVMetadataFormatID3Metadata];`
with...
`NSArray *origMetadata =
[asset2 metadataForFormat:AVMetadataFormatiTunesMetadata];`
and load an AAC file rather than an MP3 file, it works. Obviously I am missing something here. Any help would be appreciated. Thank you.
Hi i am working on application in which , i have to upload a sound file to Facebook.
Please ,provide me a better solution, whether it is possible to share a sound file on Facebook or not.
Thanks in advance
Facebook does not have sound uploading. You could always upload the sound file elsewhere and use Facebook to share the link to it.
if you check the webApps for twitter/facebook, they does not provide any means to UPLOAD an audio file.
Twittier allows only text post and on the other hand, Facebook allow Image/Video to be uploaded.
In the light of these facts, I do not think it is possible without a url share.
It is not possible to upload audio files to Facebook, only photos and videos are allowed. However, another solution would be to upload the audio file somewhere else and then use the Facebook API to post a link using that reference. One place you may wish to look to upload audio is http://developers.soundcloud.com/
Use AVAssetExportSession, create a movie with the sound file and then upload it to Facebook.
This is possible to do but it is a bit of a pain. To do this you must convert the audio file into a video file and then post it to Facebook as a video.
First we need to have access to our audioFile, you should already have this, if not then there are a lot of Stackoverflow questions devoted to this, I won't complicate matters by going off track. We then create a NSURL to a video in our documents. In this case we have an video named video_base.mp4 which has been designed to be a nice background for our audio track. Finally we merge the files before sharing the returned file to Facebook.
- (IBAction)shareToFacebook:(id)sender {
// You should already have your audio file saved
NSString * songFileName = [self getSongFileName];
NSArray * searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentPath = [searchPaths objectAtIndex:0];
NSString * file = [documentPath stringByAppendingPathComponent:songFileName];
NSURL * audioFileURL = [NSURL fileURLWithPath: audioFile];
NSURL * videoFileURL = [NSURL fileURLWithPath:[NSFileManager getFilePath:#"video_base.mp4" withFolder:#""]];
[self mergeAudio:audioFileURL andVideo:videoFileURL withSuccess:^(NSURL * url) {
// Now we have the URL of the video file
[self shareVideoToFacebook:url];
}];
}
Credit to #dineshprasanna for this part of the code which can be found here. We want to merge our audio and video and then save them to a path. We then return the exportURL in the completion block.
- (void)mergeAudio: (NSURL *)audioURL andVideo: (NSURL *)videoURL withSuccess:(void (^)(NSURL * url))successBlock {
AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audioURL options:nil];
AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:videoURL options:nil];
AVMutableComposition * mixComposition = [AVMutableComposition composition];
AVMutableCompositionTrack * compositionCommentaryTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration)
ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]
atTime:kCMTimeZero error:nil];
AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]
atTime:kCMTimeZero error:nil];
AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition
presetName:AVAssetExportPresetHighestQuality];
NSString * videoName = #"export.mov";
NSString * exportPath = [NSTemporaryDirectory() stringByAppendingPathComponent:videoName];
NSURL * exportUrl = [NSURL fileURLWithPath:exportPath];
if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
}
_assetExport.outputFileType = #"com.apple.quicktime-movie";
_assetExport.outputURL = exportUrl;
_assetExport.shouldOptimizeForNetworkUse = YES;
[_assetExport exportAsynchronouslyWithCompletionHandler: ^(void ) {
if(successBlock) successBlock(exportUrl);
}];
}
Finally we want to save our return videoURL to Facebook. It is worth noting that we need a few libraries to be added for this functionality to work:
#import <AssetsLibrary/AssetsLibrary.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKShareKit/FBSDKShareKit.h>
We then share the merged file to Facebook:
- (void)shareVideoToFacebook: (NSURL *)videoURL {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
ALAssetsLibraryWriteVideoCompletionBlock videoWriteCompletionBlock = ^(NSURL *newURL, NSError *error) {
if(error) {
NSLog( #"Error writing image with metadata to Photo Library: %#", error );
} else {
NSLog( #"Wrote image with metadata to Photo Library %#", newURL.absoluteString);
FBSDKShareDialog *shareDialog = [[FBSDKShareDialog alloc]init];
NSURL *videoURL = newURL;
FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
video.videoURL = videoURL;
FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
content.video = video;
[FBSDKShareDialog showFromViewController:self
withContent:content
delegate:nil];
}
};
if([library videoAtPathIsCompatibleWithSavedPhotosAlbum:videoURL]) {
[library writeVideoAtPathToSavedPhotosAlbum:videoURL
completionBlock:videoWriteCompletionBlock];
}
}
This should open up the Facebook app and then allow the user to share their audio file on their wall with a background of the video stored in your app.
Obviously everyone's project is different, this means you might not be able to copy paste this code exactly into your project. I have tried to split up the process meaning it should be easy to extrapolate to get audio messages uploading successfully.
Within my App I'm using the Camera to take several pictures. These pictures need to be sended in one time. For that reason I'm trying to implement a function to compress the photo's I took.
I've been looking on the internet for several libraries which I could use within my project. I came out with Objective Zip (http://code.google.com/p/objective-zip/wiki/GettingStarted). However the only thing I succeeded was compressing (or decompressing) text-files. But compressing (or decompressing) photo's is not mentioned.
I've succeeded with converting my token photo's to a NSData object. Now i want to compress them to a Zip file. Is there anyone who have had experience with these kind of functions.
Help is greatly appreciated!
Edit
I'm now using the Objective Zip library but my App keeps crashing. Still getting the known error "Thread 1: Program reveived signal : "SIGARBT" ". I'm trying to zip one image I took with the camera and stored in the documents directory.
Within the snippet you can see that I'm calling the photo I took and zipping it with the ZipFile method. In the end I'm sending my zip-file as an email attachment.
Here's a snippet of my code:
-(IBAction)sendID{
NSString *docDir3 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *docDir4 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath3 = [NSString stringWithFormat:#"%#/photo.png",docDir3];
// Create the zip file
ZipFile *zipFile = [[ZipFile alloc] initWithFileName:docDir4 mode:ZipFileModeCreate];
// Read the files in the data directory
NSError *error = nil;
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pngFilePath3 error:&error];
//ZipWriteStream *stream1= [zipFile writeFileInZipWithName:#"abc.txt" fileDate:[NSDate //dateWithTimeIntervalSinceNow:-86400.0] compressionLevel:ZipCompressionLevelBest];
// Write each file to our zip
for (NSString *filename in files) {
// Write the file
ZipWriteStream *stream = [zipFile writeFileInZipWithName:filename compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:pngFilePath3];
[stream writeData:data];
[stream finishedWriting];
}
// Close the zip file
[zipFile close];
NSData *data = [NSData dataWithContentsOfFile:#"Test.zip"];
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate=self;
//NSData *imageData = UIImageJPEGRepresentation(viewImage, 1);
[picker addAttachmentData:data mimeType:#"application/zip" fileName:#"Test.zip"];
Class mailclass = (NSClassFromString(#"MFMailComposeViewController"));
if([mailclass canSendMail]){
[self presentModalViewController:picker animated:YES];
}
}
Hope anyone can help me out.
I know this is an old thread, but here's how I zip up multiple files using Objective-Zip:
- (NSString*) objectiveZip:(NSArray*)passedFiles
{
NSString *outputPath = [self getOutputDirectory];
NSString *zipFileName = #"MyZip.zip";
outputPath = [outputPath stringByAppendingString:zipFileName];
//Create a zip file for writing
ZipFile *zipFile= [[ZipFile alloc] initWithFileName:outputPath mode:ZipFileModeCreate];
//Add all the files, write to its stream and close it
for(NSString *string in passedFiles)
{
NSString *fileName = string;
NSLog(#"Add file to zip: %#", fileName);
ZipWriteStream *stream1= [zipFile writeFileInZipWithName:fileName fileDate:[NSDate dateWithTimeIntervalSinceNow:-86400.0] compressionLevel:ZipCompressionLevelBest];
[stream1 writeData:[NSData dataWithContentsOfURL:[NSURL URLWithString:info.pdfUrl]]];
[stream1 finishedWriting];
}
// Close the zip file
[zipFile close];
return outputPath;
}
The best zip lib I've found is SSZipArchive. Give that one a shot.
NSString *temp=[[[makeZip textFieldAtIndex:0]text]stringByAppendingPathExtension:#"zip"];
NSString *zippedPath = [pathString stringByAppendingPathComponent:temp];
NSMutableArray *inputPaths=[[NSMutableArray alloc]init];
for (int i=0; i<[selectedRows count]; i++) {
[inputPaths addObject:[pathStringstringByAppendingPathComponent:[selectedRows objectAtIndex:i]]];
}
if (![[NSFileManager defaultManager] fileExistsAtPath:zippedPath])
{
[SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths];
[directoryContents addObject:temp];
[tblview reloadData];
}
I created an app which get the url of my youtube videos in the text field using GData Client Library. Now i want to shorten that url using bitly api.. But i don't have an idea about that.
if anybody done it before me, please tell me how you did it.
Thanks,
Chakradhar.
This is a quick and easy way of doing it.
You will need to register with bit.ly and obtain a login name and API key.
NSString *username = #"user";
NSString *apiKey = #"R_11111111111111";
NSString *url = #"yoururl.com";
NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://api.bit.ly/v3/shorten?login=%#&apikey=%#&longUrl=%#&format=txt", username, apiKey, url]] encoding:NSUTF8StringEncoding error:nil];
Here is an iOS wrapper for bit.ly api https://github.com/st3fan/iphone-bitly
This has worked well for me, and since it is a synchroeous request there is a slight delay to fetch the link so you may want to display a Progress HUD:
NSString *accessToken = YOUR_ACCESS_TOKEN;
NSString *url = YOUR_URL;
NSString *bitlyRequest = [NSString stringWithFormat:#"https://api-ssl.bitly.com/v3/shorten?access_token=%#&longUrl=%#",accessToken, url];
NSString *bitlyResponse = [NSString stringWithContentsOfURL:[NSURL URLWithString:bitlyRequest] encoding:NSUTF8StringEncoding error:nil];
NSData *data = [bitlyResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *bitlyDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *bitlyUrl = bitlyDictionary[#"data"][#"url"];
I suggest you start with theri API documentation.
I have some source code to get the file name of an url
for example:
http://www.google.com/a.pdf
I hope to get a.pdf
because the way to join 2 NSStrings I can get is 'appendString' which only for adding a string at right side, so I planned to check each char one by one from the right side of string 'http://www.google.com/a.pdf', when it reach at the char '/', stop the checking, return string fdp.a , after that I change fdp.a to a.pdf
source codes are below
-(NSMutableString *) getSubStringAfterH : originalString:(NSString *)s0
{
NSInteger i,l;
l=[s0 length];
NSMutableString *h=[[NSMutableString alloc] init];
NSMutableString *ttt=[[NSMutableString alloc] init ];
for(i=l-1;i>=0;i--) //check each char one by one from the right side of string 'http://www.google.com/a.pdf', when it reach at the char '/', stop
{
ttt=[s0 substringWithRange:NSMakeRange(i, 1)];
if([ttt isEqualToString:#"/"])
{
break;
}
else
{
[h appendString:ttt];
}
}
[ttt release];
NSMutableString *h1=[[[NSMutableString alloc] initWithFormat:#""] autorelease];
for (i=[h length]-1;i>=0;i--)
{
NSMutableString *t1=[[NSMutableString alloc] init ];
t1=[h substringWithRange:NSMakeRange(i, 1)];
[h1 appendString:t1];
[t1 release];
}
[h release];
return h1;
}
h1 can reuturn the coorect string a.pdf, but if it returns to the codes where it was called, after a while system reports
'double free
*** set a breakpoint in malloc_error_break to debug'
I checked a long time and foudn that if I removed the code
ttt=[s0 substringWithRange:NSMakeRange(i, 1)];
everything will be Ok (of course getSubStringAfterH can not returns the corrent result I expected.), no error reported.
I try to fix the bug a few hours, but still no clue.
Welcome any comment
Thanks
interdev
The following line does the job if url is a NSString:
NSString *filename = [url lastPathComponent];
If url is a NSURL, then the following does the job:
NSString *filename = [[url path] lastPathComponent];
Try this:
Edit: from blow comment
NSString *url = #"http://www.google.com/a.pdf";
NSArray *parts = [url componentsSeparatedByString:#"/"];
NSString *filename = [parts lastObject];
I think if you have already had the NSURL object, there is lastPathComponent method available from the iOS 4 onwards.
NSURL *url = [NSURL URLWithString:#"http://www.google.com/a.pdf"];
NSString *filename = [url lastPathComponent];
Swift 3
Let's say that your url is http://www.google.com/a.pdf
let filename = url.lastPathComponent
\\filename = "a.pdf"
This is more error free and meant for getting the localized name in the URL.
NSString *localizedName = nil;
[url getResourceValue:&localizedName forKey:NSURLLocalizedNameKey error:NULL];
I haven't tried this yet, but it seems like you might be trying to do this the hard way. The iPhone libraries have the NSURL class, and I imagine that you could simply do:
NSString *url = [NSURL URLWithString:#"http://www.google.com/a.pdf"];
NSString *path = [url path];
Definitely look for a built in function. The libraries have far more testing and will handle the edge cases better than anything you or I will write in an hour or two (generally speaking).