I am working with an iOS application in which I have to upload images on Box Service. After authentication process when I uploaded images from the NSBundle, it uploaded successfully.
when I uploaded from a path image get uploaded but only file is created, no data is uploaded.
Below is my uploaded method:
-m(void)uploadimages:(UIImage*)image
{
BoxFileBlock fileBlock = ^(BoxFile *file)
{
[self fetchFolderItemsWithFolderID:self.folderID name:self.navigationController.title];
dispatch_sync(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"File Upload Successful" message:[NSString stringWithFormat:#"File has id: %#", file.modelID] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
});
};
BoxAPIJSONFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
{
BOXLog(#"status code: %li", (long)response.statusCode);
BOXLog(#"upload response JSON: %#", JSONDictionary);
};
BoxFilesRequestBuilder *builder = [[BoxFilesRequestBuilder alloc] init];
NSInteger randomNumber = arc4random() % 100;
NSString *filename = [NSString stringWithFormat:#"PicBackMan-%ld.jpg",(long)randomNumber];
builder.name = filename;
builder.parentID = self.folderID;
NSLog(#"builder.parentID : %#",builder.parentID);
NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
path = [[pathList objectAtIndex:0] stringByAppendingPathComponent:#"image.jpg"];
NSLog(#"Path o/p is %#",path);
NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath: path];
NSLog(#"inputStream DIRECT : %#",inputStream);
NSError *error;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&error];
if (!error) {
if (fileAttributes != nil) {
NSLog(#"File attributes found.");
} else {
NSLog(#"File attributes not found.");
}
} else {
NSLog(#"%#", [error localizedDescription]);
long long contentLength = [[fileAttributes objectForKey:NSFileSize] longLongValue];
NSLog(#"fileAttributes : %#",fileAttributes);
NSLog(#"contentLength : %lld",contentLength);
[[BoxSDK sharedSDK].filesManager uploadFileWithInputStream:inputStream contentLength:contentLength MIMEType:nil requestBuilder:builder success:fileBlock failure:failureBlock progress:nil];
}
I am getting the output, but my file is not uploaded with data, only an image of file with name created.
I am getting following output in log:
builder.parentID : 2323165189
2014-08-19 17:25:58.431 BoxSDKSampleApp[17252:1243051] /Users/bettermac9/Library/Application Support/iPhone Simulator/7.1-64/Applications/30DFB367-599B-4F39-AD62-D27B1081FE99/Documents/image.jpg
2014-08-19 17:25:58.432 BoxSDKSampleApp[17252:1243051] inputStream DIRECT : <__NSCFInputStream: 0x7f8f7ae5db00>
2014-08-19 17:25:58.432 BoxSDKSampleApp[17252:1243051] The operation couldn’t be completed. (Cocoa error 260.)
2014-08-19 17:25:58.432 BoxSDKSampleApp[17252:1243051] fileAttributes : (null)
2014-08-19 17:25:58.432 BoxSDKSampleApp[17252:1243051] contentLength : 0
Please help me out, as per my knowledge I think I am doing any mistake in reading the file from path and sending to NSinputstream. Please help me out.
Thank you
Related
I'm trying to download video from youtube but getting error.
Error mention in code
my code
-(void)downloadVideo{
LBYouTubeExtractor *extractor = [[LBYouTubeExtractor alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:(#"https://www.youtube.com/watch?v=%#"), videoIdToDownload ]] quality:LBYouTubeVideoQualityLarge];
[extractor extractVideoURLWithCompletionBlock:^(NSURL *videoURL, NSError *error) {
if(!error) {
NSLog(#"Did extract video URL using completion block: %#", videoURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError* error = nil;
NSData* data1 = [NSData dataWithContentsOfURL:videoURL options:NSDataReadingUncached error:&error]; //data1 is nill
if (error) { //Error Domain=NSCocoaErrorDomain Code=256 "The file “3gpp;+codecs="mp4v.20.3,+mp4a.40.2"&fallback_host=tc.v8.cache4.googlevideo.com&itag=36” couldn’t be opened."
NSLog(#"error=%#", error);
}else{
NSString *filename = [NSString stringWithFormat:(#"video_%#.mp4"), videoIdToDownload ];
[data1 writeToFile:[dirPath stringByAppendingPathComponent:filename] atomically:YES];
NSLog(#"File %# successfully saved", filename);
}
});
} else {
NSLog(#"Failed extracting video URL using block due to error:%#", error);
}
}];
}
using this lib
https://github.com/larcus94/LBYouTubeView
If anyone now solution please help me.
Thanks
I use GoldRaccoon for ftp-upload in my iOS-Application. The filetransfer works perfekt with txt-files up to many mb size. But images and pdf-files would be corrupted when they be uploaded.
There is no error and the upload seems to be successfull.
When i look into the iPad in the folder of the application (with iExplorer), there the files are good. Its also equal how big the size of the image is. Also its equal if it is a jpg or a png.
Also the files all existing when I start the upload.
- (void)uploadFilesToFTP:(Objekt *)objekt withCsvFilePath:(NSString *)csvLocalFilePath {
__block typeof(self) bself = self;
[self.library enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:self.albumName]) {
InfoLogMy(#"found album %#", self.albumName);
self.groupToAddTo = group;
}
}
failureBlock:^(NSError* error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Fehler" message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
return;
}];
// dateien
InfoLogMy("Count of files %d", objekt.dateien.count);
for (Datei *datei in objekt.dateien)
{
InfoLogMy(#"Upload starts");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dateiPath = [documentsDirectory stringByAppendingPathComponent:datei.dateiname];
NSError *error;
NSData *data = [[NSData alloc] initWithContentsOfFile:dateiPath options:NSDataReadingUncached error:&error];
if( [[NSFileManager defaultManager] fileExistsAtPath:dateiPath] )
{
if (!error) {
if (datei.zimmer != nil) {
// original image
UIImage *originalImage = [UIImage imageWithData:data];
__block typeof(self) bself = self;
//Bild wird in das Photoalbum des iPads als Sicherung abgelegt.
//Dies ist nicht mit PDF-Dokumenten möglich
[self.library writeImageToSavedPhotosAlbum:[originalImage CGImage]
metadata:nil
completionBlock:^(NSURL* assetURL, NSError* error) {
if (error.code == 0) {
// try to get the asset
[self.library assetForURL:assetURL
resultBlock:^(ALAsset *asset) {
// assign the photo to the album
[bself.groupToAddTo addAsset:asset];
}
failureBlock:^(NSError* error) {
InfoLogMy("failed to retrieve image asset:\nError: %# ", [error localizedDescription]);
}];
}
else {
InfoLogMy("saved image failed.\nerror code %i\n%#", error.code, [error localizedDescription]);
}
}];
}
// copy of image
NSString *filenameCopy = [NSString stringWithFormat:#"copy-%#", datei.dateiname];
NSString *localFilePathCopy = [documentsDirectory stringByAppendingPathComponent:filenameCopy];
BOOL copyFileExists = [[NSFileManager defaultManager] fileExistsAtPath:localFilePathCopy];
BOOL hasPaths = ([[datei.zeichnungen allObjects] count] > 0);
BOOL hasSymbols = ([[datei.symbole allObjects] count] > 0);
NSString *fileExtension = [datei.dateiname substringWithRange:NSMakeRange(datei.dateiname.length - 3, 3)];
BOOL isPDF = ([fileExtension isEqualToString:#"pdf"]);
if (copyFileExists == YES && (hasPaths == YES || hasSymbols == YES|| isPDF == YES)) {
NSError *error;
NSData *dataCopy = [[NSData alloc] initWithContentsOfFile:localFilePathCopy options:NSDataReadingUncached error:&error];
if (isPDF == NO) {
UIImage *copyImage = [UIImage imageWithData:dataCopy];
[self.library writeImageToSavedPhotosAlbum:[copyImage CGImage]
metadata:nil
completionBlock:^(NSURL* assetURL, NSError* error) {
if (error.code == 0) {
InfoLogMy(#"saved image completed:\nurl: %#", assetURL);
// try to get the asset
[self.library assetForURL:assetURL
resultBlock:^(ALAsset *asset) {
// assign the photo to the album
[bself.groupToAddTo addAsset:asset];
}
failureBlock:^(NSError* error) {
InfoLogMy(#"failed to retrieve image asset:\nError: %# ", [error localizedDescription]);
}];
}
else {
InfoLogMy(#"saved image failed.\nerror code %i\n%#", error.code, [error localizedDescription]);
}
}];
}
if (!error) {
[self.requestsManager addRequestForUploadFileAtLocalPath:localFilePathCopy toRemotePath:[NSString stringWithFormat:#"%#%#", kFtpPathOutbox, filenameCopy]];
}
}
else
{
//Wenn die Datei keine Zuordnung zu einem Zimmer hat.
if (datei.zimmer != nil)
{
[self.requestsManager addRequestForUploadFileAtLocalPath:dateiPath toRemotePath:[NSString stringWithFormat:#"%#%#", kFtpPathOutbox, datei.dateiname]];
}
}
} else {
// TO DO: Alert mit Fehler
return;
}
}
else
{
InfoLogMy(#"Datei existiert leider nicht");
[Mbs writeLog:[NSString stringWithFormat:#"Datei existiert nicht (%#)", datei.dateiname]];
}
}
NSArray *parts = [csvLocalFilePath componentsSeparatedByString:#"/"];
NSString *remotePath = [NSString stringWithFormat:#"%#%#", kFtpPathOutbox, [parts lastObject]];
[self.requestsManager addRequestForUploadFileAtLocalPath:csvLocalFilePath toRemotePath:remotePath];
self.requestsManagerFailed = NO;
[self.requestsManager startProcessingRequests];
}
I using a Core Data with 2 entities One is my archive, have reference for image, name and NSNumber the second Entity is mi numeric balance.
In the Archive view i can load Archive entity in to a UITable View, if i tap on my cell i have the perfect detail and my button to set the Card.
In the detail I've the Delete button, this have a function to delete a single card and in to Balance entity change the numeric value.
If i try to delete is working well and the Balance load good the new value, but is i add new card, my balance add a new value plus the last value erased:
Start App add my card with Name, Image and value (10), Balance show 1 card, total 10, is ok.
Go to my archive select my card and Delete, now i have empty archive, and my Balance showing 0 card and 0 value, now if i add other card exaple value 10, my balance sowing 2card and 20value.
this is the code using to delete:
- (IBAction)delete:(id)sender {
NSError *error;
NSManagedObjectContext *context = [self managedObjectContext];
[context deleteObject:loadA[_currentRecord]];
//image remover from documents folder//
NSString *imageRemover = [[self docsDir]stringByAppendingPathComponent:nomeSc.text];
[[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:#"%#.jpg", imageRemover] error:&error];
//----------------------------------//
if (![context save:&error]){
NSLog(#"Save Error, please retry: %#", [error localizedDescription]);
}
[self refreshBalance];
_currentRecord =-1;
}
- (void)refreshBalance:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
if (_currentRecord <= -1) {
modifyA = loadA[_currentRecord];
modifyB = loadB[currentBalance];
}
int oldBet = [betOld.text intValue];
int cardBetting = [modifyB.totalCards intValue];
int amauntBet = [blDetail[0] intValue];
modifyB.totBet = [NSNumber numberWithInteger:amauntBet - oldBet];
modifyB.totCards = [NSNumber numberWithInt:cardBetting -1];
}
NSError *error;
if (![context save:&error]) {
NSLog(#"Errore durante il salvataggio: %#", [error localizedDescription]);
}
_currentRecord = -1;
_currentBalance = -1;
[self.navigationController popViewControllerAnimated:YES];
}
**********THIS IS A FUNCTION TO SAVE*****************
- (IBAction)onSave:(id)sender{
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imageName = self.name.text;
NSString* foofile = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.jpg", imageName]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
if (fileExists == YES){
NSString *titolo = #"Warning";
NSString *messaggio = [NSString stringWithFormat:#"Your name ( %# ) exist, please changeit!", imageName];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
} else
if (nomeGiocata.text.length == 0 || importoGiocato.text.length == 0 ) {
NSString *titolo = #"Warning";
NSString *messaggio = #"There are empty fileds!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
} else {
NSString *imageName = self.nomeGiocata.text;
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
UIImage * imageToSave = self.imageViewPick.image;
NSData * binaryImageData = UIImageJPEGRepresentation(imageToSave, 1.0);
[binaryImageData writeToFile:[basePath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.jpg", imageName]] atomically:YES];
NSManagedObjectContext *context = [self managedObjectContext];
[self.managedObjectContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
newScheda = [NSEntityDescription
insertNewObjectForEntityForName:#"Archive"
inManagedObjectContext:context];
newScheda.immagine = [NSString stringWithFormat:#"%#.jpg", imageName];
newScheda.nome = nomeGiocata.text;
int bet = [importoGiocato.text intValue];
newScheda.giocata = [NSNumber numberWithInt:giocata];
addSched = balance[currentRecord];
int insert = [addSched.totScommesso intValue];
addSched.totScommesso = [NSNumber numberWithInt:insert + bet];
int aggiungiSched = [addSched.totSchedGiocate intValue];
addSched.totSchedGiocate = [NSNumber numberWithInt:aggiungiSched + 1];
int balance = [addSched.totBilancio intValue];
addSched.totBilancio = [NSNumber numberWithInt:balance + giocata];
NSError *error;
if (![context save:&error]) {
NSLog(#"Error during the process: %#", [error localizedDescription]);
}
NSString *titolo = #“MyApp";
NSString *messaggio = #"Saved!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
[self clearFields];
}
How can empty a cache when i delete my Record? or have other idea?
I'm using Facebook SDK 3.6 within an iOS 6.3 app to upload a video to Facebook.
I've looked over many Stack Overflow posts about this but they are all years old and using much older Facebook SDKs.
Sometimes it works, other times it fails with the following message:
unexpected error:Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x1e2affc0 {com.facebook.sdk:HTTPStatusCode=500, com.facebook.sdk:ParsedJSONResponseKey={
body = {
"error_code" = 1;
"error_msg" = "An unknown error occurred";
};
code = 500;
}, com.facebook.sdk:ErrorSessionKey=, expirationDate: 4001-01-01 00:00:00 +0000, refreshDate: 2013-07-30 10:54:22 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(
"publish_stream"
)>}
Here is my code:
FBRequestConnection *_currentConnection;
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_stream"]
defaultAudience:FBSessionDefaultAudienceOnlyMe
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
NSError *attributesError;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
NSLog(#"file size: %lld", fileSize);
NSString *filename = [url lastPathComponent];
NSLog(#"filename: %#", filename);
NSString *mimeType = [self MIMETypeForFilename:filename
defaultMIMEType:#"video/mp4"];
NSLog(#"mime type: %#", mimeType);
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, filename,
mimeType, #"contentType",
self.song.name, #"title",
_videoDescription, #"description",
nil];
FBRequest *request = [FBRequest requestWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"];
_currentConnection = [request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
self.stageLabel.text = #"";
NSLog(#"result: %#, error: %#", result, error);
if(error) {
// Facebook SDK * error handling *
// if the operation is not user cancelled
if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
[self showAlert:#"Video Post" result:result error:error];
}
self.uploadBarButtonItem.enabled = YES;
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Video Uploaded" message:#"Video has been uploaded"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[self.delegate facebookUploaderUploadSucceeded:self];
}
// Delete the temp video
NSError *err;
[[NSFileManager defaultManager] removeItemAtURL:_sourceURL error:&err];
NSLog(#"Deleting video %#: %#", _sourceURL, [err localizedDescription]);
}];
}];
}
}];
This Code is Tested successfully On FaceBook SDK 3.14.1
-(void)shareOnFaceBook
{
//sample_video.mov is the name of file
NSString *filePathOfVideo = [[NSBundle mainBundle] pathForResource:#"sample_video" ofType:#"mov"];
NSLog(#"Path Of Video is %#", filePathOfVideo);
NSData *videoData = [NSData dataWithContentsOfFile:filePathOfVideo];
//you can use dataWithContentsOfURL if you have a Url of video file
//NSData *videoData = [NSData dataWithContentsOfURL:shareURL];
//NSLog(#"data is :%#",videoData);
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video name ", #"name",
#"description of Video", #"description",
nil];
if (FBSession.activeSession.isOpen)
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
NSLog(#"RESULT: %#", result);
[self throwAlertWithTitle:#"Success" message:#"Video uploaded"];
}
else
{
NSLog(#"ERROR: %#", error.localizedDescription);
[self throwAlertWithTitle:#"Denied" message:#"Try Again"];
}
}];
}
else
{
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions",
nil];
// OPEN Session!
[FBSession openActiveSessionWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (error)
{
NSLog(#"Login fail :%#",error);
}
else if (FB_ISSESSIONOPENWITHSTATE(status))
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
[self throwAlertWithTitle:#"Success" message:#"Video uploaded"];
NSLog(#"RESULT: %#", result);
}
else
{
[self throwAlertWithTitle:#"Denied" message:#"Try Again"];
NSLog(#"ERROR: %#", error.localizedDescription);
}
}];
}
}];
}
}
And I GOT Error:
The operation couldn’t be completed. (com.facebook.sdk error 5.)
It happens when facebook is being inited. Next time i open my app, it works fine, its always the first time. Tried everything in app, but it seems to be on the Facebook SDK side.
Few causes for seeing com.facebook.sdk error 5:
Session is is not open. Validate.
Facebook has detected that you're spamming the system. Change video name.
Facebook has a defined limit using the SDK. Try a different app.
Wrong publish permission. Give publish_actions a spin.
I am looking for an example where a video is posted to facebook using iOS 6 & SLRequest. I already have my code working for uploading a photo.
Thanks in advance!
For sharing a Video to FB :
Create an app on developer.facebook.com
mention the AppId in appName-info.plist
mention app BundleID in develper.facebook.com of your app page under iOS platform
Then on coding:
we have to request for read permission then write permission .
-(void)shareOnFB
{
__block ACAccount * facebookAccount;
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
NSDictionary *emailReadPermisson = [[NSDictionary alloc] initWithObjectsAndKeys:
FB_APP_ID,ACFacebookAppIdKey,
#[#"email"],ACFacebookPermissionsKey,
ACFacebookAudienceFriends,ACFacebookAudienceKey,
nil];
NSDictionary *publishWritePermisson = [[NSDictionary alloc] initWithObjectsAndKeys:
FB_APP_ID,ACFacebookAppIdKey,
#[#"publish_stream"],ACFacebookPermissionsKey,
ACFacebookAudienceFriends,ACFacebookAudienceKey,
nil];
ACAccountType *facebookAccountType = [accountStore
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
//Request for Read permission
[accountStore requestAccessToAccountsWithType:facebookAccountType options:emailReadPermisson completion:^(BOOL granted, NSError *error) {
if (granted)
{
//Request for write permission
[accountStore requestAccessToAccountsWithType:facebookAccountType options:publishWritePermisson completion:^(BOOL granted, NSError *error) {
if (granted)
{
NSArray *accounts = [accountStore
accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
NSLog(#"access to facebook account ok %#", facebookAccount.username);
[self uploadWithFBAccount:facebookAccount];
}
else
{
NSLog(#"access to facebook is not granted");
// extra handling here if necesary
dispatch_async(dispatch_get_main_queue(), ^{
// Fail gracefully...
NSLog(#"%#",error.description);
[self errorMethodFromFB:error];
});
}
}];
}
else
{
[self errorMethodFromFB:error];
}
}];
}
Then Handle the error method from facebook
-(void)errorMethodFromFB:(NSError *)error
{
NSLog(#"access to facebook is not granted");
// extra handling here if necesary
dispatch_async(dispatch_get_main_queue(), ^{
// Fail gracefully...
NSLog(#"%#",error.description);
if([error code]== ACErrorAccountNotFound)
[self throwAlertWithTitle:#"Error" message:#"Account not found. Please setup your account in settings app."];
if ([error code] == ACErrorAccessInfoInvalid)
[self throwAlertWithTitle:#"Error" message:#"The client's access info dictionary has incorrect or missing values."];
if ([error code] == ACErrorPermissionDenied)
[self throwAlertWithTitle:#"Error" message:#"The operation didn't complete because the user denied permission."];
else
[self throwAlertWithTitle:#"Error" message:#"Account access denied."];
});
}
Then message alert
-(void)throwAlertWithTitle:(NSString *)title message:(NSString *)msg
{
[[[UIAlertView alloc]initWithTitle:title message:msg delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil]show];
}
Handle Uploading method
-(void)uploadWithFBAccount:(ACAccount *)facebookAccount
{
ACAccountCredential *fbCredential = [facebookAccount credential];
NSString *accessToken = [fbCredential oauthToken];
NSURL *videourl = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/me/videos?access_token=%#",accessToken]];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* foofile = [documentsDirectory stringByAppendingPathComponent:#"me.mov"];
BOOL fileExists = [fileManager fileExistsAtPath:foofile];
if (fileExists)
{
NSLog(#"file saved");
}
NSString *filePath = foofile;
NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:filePath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *params = #{
#"title": #"Me silly",
#"description": #"Me testing the video upload to Facebook with the new Social Framework."
};
SLRequest *uploadRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:videourl
parameters:params];
[uploadRequest addMultipartData:videoData
withName:#"source"
type:#"video/quicktime"
filename:[pathURL absoluteString]];
uploadRequest.account = facebookAccount;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
[uploadRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if(error)
{
NSLog(#"Error %#", error.localizedDescription);
}
else
{
[[[UIAlertView alloc]initWithTitle:#"Congratulations!" message:#"Your video is suucessfully posted to your FB newsfeed" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil]show];
NSLog(#"%#", responseString);
}
}];
});
}
Check out this post: Video Upload with SLRequest
It clearly points out how to use it with the Social Framework integrated in iOS 6 (SLRequest) and even also how to use Facebooks SDK.