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

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.

Related

Getting error while fetching data from server using NSURLSession Datatask in objective c

I was trying to load data for the table using values from server.I am using NSURLSession datatask with completion handler. Whenever it reaches the nsurlsession, it shows error.This is the code which i used for getting data.
- (void)geturl:(NSString *)urlvalue datavalues:(NSString *)string fetchGreetingcompletion:(void (^)(NSDictionary *dictionary, NSError *error))completion{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#?%#",common.getUrlPort,urlvalue,common.getappversion]];
NSLog(#"url=%#",url);
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest addValue:common.getauthtoken forHTTPHeaderField:#"Authorization"];
//Create POST Params and add it to HTTPBody
[urlRequest setHTTPMethod:#"GET"];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) {
NSLog(#"Response:%# %#\n", response, connectionError);
if (data.length > 0 && connectionError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSString *code = [NSString stringWithFormat:#"%#",[greeting valueForKey:#"code"]];
if([code isEqualToString:#"-1"]){
[self loaderrorview:greeting];
}
else{
if (completion)
completion(greeting, connectionError);
}
}
else if(data == nil){
NSDictionary *errorDict=[[NSDictionary alloc]initWithObjectsAndKeys:#"Server Connection Failed",#"error", nil];
if (completion)
completion(errorDict,connectionError);
}
else
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if (completion)
completion(greeting, connectionError);
}
}];
[dataTask resume];
}
The code which i used for getting data from server:
-(void)getdataexplore{
if (!common.checkIfInternetIsAvailable) {
[self.view makeToast:Nointernetconnection];
} else {
NSLog(#"There is internet connection");
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
[SVProgressHUD showWithStatus:#"Loading..."];
[apiservice geturl:loadexploredata datavalues:nil fetchGreetingcompletion:^(NSDictionary *dictionary, NSError *error) {
//NSLog(#"Test %# Error %#",dictionary,error);
if(error == nil){
authDictionary = dictionary;
[self loaddata];
}
else{
[SVProgressHUD dismiss];
[view_business makeToast:#"Request timed out" duration:2.0 position:CSToastPositionCenter];
}
}];
}
}
The code which i used for storing server data to array:
-(void)loaddata
{
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
[SVProgressHUD showWithStatus:#"Loading..."];
//[SVProgressHUD dismiss];
NSString *msg = [authDictionary valueForKey:#"msg"];
NSString *code = [NSString stringWithFormat:#"%#",[authDictionary valueForKey:#"code"]];
if([code isEqualToString:#"201"]){
NSDictionary *explore = [authDictionary valueForKey:#"explore_obj"];
arr_CBcategories = [explore valueForKey:#"cb_categories"];
[common setarrCBCaterory:arr_CBcategories];
arr_CBcategoryid = [arr_CBcategories valueForKey:#"id"];
[common setarrCateroryID:arr_CBcategoryid];
arr_CBcategorytitle = [arr_CBcategories valueForKey:#"title"];
[common setarrCaterorytitle:arr_CBcategorytitle];
arr_CBcategoryslug = [arr_CBcategories valueForKey:#"slug"];
[common setarrCateroryslug:arr_CBcategoryslug];
arr_CBcategoryimage = [arr_CBcategories valueForKey:#"image"];
[common setarrCateroryimage:arr_CBcategoryimage];
arr_CBcategorycode = [arr_CBcategories valueForKey:#"code"];
}
I am getting error like "Unable to run main thread". Any solution for this.

How to set a default user in xcode7 with the help of objective c?

I'm trying to build and login and logout application, but not able to login please help me to set default user id and password through which i would be able go to the next page
You can try this code it will help you :
-(void)login
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://www.example.com/pm/api/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=admin&password=123456&api_key=bf45c093e542f057c123ae7d6"];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
if(checkBoxSelected == YES)
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString* textField1Text = usernameField.text;
[defaults setObject:textField1Text forKey:#"textField1Text"];
NSString *textField2Text = passwordField.text;
[defaults setObject:textField2Text forKey:#"textField2Text"];
[defaults synchronize];
}
NSString *strID = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField1Text"];
NSString *strPWD = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField2Text"];
[[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:#"user_id"] forKey:#"CurrentUserLoggedIn"];
NSString *strUser = [[NSUserDefaults standardUserDefaults] stringForKey:#"CurrentUserLoggedIn"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self saveLoginFileToDocDir:dictionary];
ItemManagement *i = [[ItemManagement alloc]init];
[self.navigationController pushViewController:i animated:YES];
}
else
{
NSLog(#"Unsuccessful, Try again.");
UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];
}
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}
- (NSDictionary *)getLoginFileFromDocDir
{
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return dict;
}
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = !checkBoxSelected;
[checkbox setSelected:checkBoxSelected];
}
to set a default user in app you may use the code below
In your AppDelegate.m
if ([[NSUserDefaults standardUserDefaults]boolForKey:#"IsFirstTime"])
{
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
ViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:#"ViewController"];
self.window.rootViewController = vc;
}
else
{
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:#"IsFirstTime"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
then #import your AppDelegate.m class to the class where you put code for login
AppDelegate *delegate;
- (void)viewDidLoad
{
[super viewDidLoad];
delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
}
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://43.252.88.251/jsonandroid/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=admin&password=123456&api_key=bf45c093e542f057c123ae7d6"];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString* textField1Text = usernamefield.text;
[defaults setObject:textField1Text forKey:#"textField1Text"];
NSString *textField2Text = passwordfield.text;
[defaults setObject:textField2Text forKey:#"textField2Text"];
[defaults synchronize];
}
NSString *strID = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField1Text"];
NSString *strPWD = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField2Text"];
[[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:#"user_id"] forKey:#"CurrentUserLoggedIn"];
NSString *strUser = [[NSUserDefaults standardUserDefaults] stringForKey:#"CurrentUserLoggedIn"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self saveLoginFileToDocDir:dictionary];
/* ItemManagement *ItemManagement = [[ItemManagement alloc]init];
[self.navigationController pushViewController:ItemManagement animated:YES];
*/
}
else
{
NSLog(#"Unsuccessful, Try again.");
/* UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];*/
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Title" message:#"Hello" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelbutton = [UIAlertAction actionWithTitle:#"" style:UIAlertActionStyleCancel handler:nil];
//UIAlertAction *oktext= [UIAlertAction actionWithTitle:oktext style:UIAlertActionStyleDefault handler:nil];
[alert addAction:cancelbutton];
//[alert addAction:oktext];
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}
- (NSDictionary *)getLoginFileFromDocDir
{
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return dict;
}

Can't load facebook profile image

I have a problem with uploading profile picture from facebook to my API and saving to Parse. This code is from Udemy. I'm using Xcode 7.2.
Error:
2016-01-18 10:14:15.296 MatchedUp[14381:5418567] Error in FB request Error Domain=com.facebook.sdk Code=5 "(null)" UserInfo={com.facebook.sdk:HTTPStatusCode=400, com.facebook.sdk:ErrorSessionKey=<PFReceptionist: 0x12663d2e0>, com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 100;
"fbtrace_id" = "FXTRrxOh0+c";
message = "(#100) Tried accessing nonexisting field (photo) on node type (User)";
type = OAuthException;
};
};
code = 400;
}}
Code:
-(void)updateUserInformation
{
//
FBRequest *request = [FBRequest requestForGraphPath:#"me/?fields=name,birthday,first_name,location,gender,interested_in,photo"];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error){
NSDictionary *userDictionary = (NSDictionary *)result;
//create URL
NSString *facebookID = userDictionary[#"id"];
NSLog(#"%#",result);
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
NSData *imageData = [NSData dataWithContentsOfURL:pictureURL];
// UIImage *fbImage = [UIImage imageWithData:imageData];
NSLog(#"%#",result);
NSMutableDictionary *userProfile = [[NSMutableDictionary alloc] initWithCapacity:8];
NSLog(#"%#",result);
if(userDictionary[#"name"]){
userProfile[kCCUserProfileNameKey] = userDictionary[#"name"];
}
if(userDictionary[#"user_birthday"]){
userProfile[kCCUserProfileBirthdayKey] = userDictionary[#"user_birthday"];
}
if(userDictionary[#"first_name"]){
userProfile[kCCUserProfileFirstNameKey] = userDictionary[#"first_name"];
}
if(userDictionary[#"location"][#"name"]){
userProfile[kCCUserProfileLocationNameKey] = userDictionary[#"location"][#"name"];
}
if(userDictionary[#"gender"]){
userProfile[kCCUserProfileGenderKey] = userDictionary[#"gender"];
}
if(userDictionary[#"interested_in"]){
userProfile[kCCUserProfileInterestedInKey] = userDictionary[#"interested_in"];
}
if([pictureURL absoluteString]){
userProfile[kCCUserProfilePictureURL] = [pictureURL absoluteString];
}
[[PFUser currentUser] setObject: userProfile forKey:kCCUserProfileKey];
[[PFUser currentUser] saveInBackground];
[self requestImage];
}
else{
NSLog(#"Error in FB request %#", error);
}
}];
}
-(void) uploadPFFileToParse:(UIImage *)image
{
NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
if(!imageData){
NSLog(#"imageData was not found");
return;
}
PFFile *photoFile = [PFFile fileWithData:imageData];
[photoFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
if(succeeded){
PFObject *photo = [PFObject objectWithClassName:kCCPhotoClassKey];
[photo setObject:[PFUser currentUser] forKey:kCCPhotoUserKey];
[photo setObject:photoFile forKey:kCCPhotoPictureKey];
[photo saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
NSLog(#"Photo saved successfully");
}];
}
}];
}
-(void) requestImage
{
PFQuery *query = [PFQuery queryWithClassName:kCCPhotoClassKey];
[query whereKey:kCCPhotoUserKey equalTo:[PFUser currentUser]];
[query countObjectsInBackgroundWithBlock:^(int number, NSError * _Nullable error) {
if(number == 0 )
{
PFUser *user = [PFUser currentUser];
self.imageData = [[NSMutableData alloc] init];
NSURL *profilePictureUrl = [NSURL URLWithString:user [kCCUserProfileKey][kCCUserProfilePictureURL]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:profilePictureUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:4.0f];
NSURLConnection *urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
if(!urlConnection){
NSLog(#"Failed to Download Picture");
}
}
}];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.imageData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
UIImage *profileImage = [UIImage imageWithData:self.imageData];
[self uploadPFFileToParse:profileImage];
}
#end
Any idea how can i fix this problem?
Thanks a lot!
Try this.
- (void)getFBProfilePicture {
NSString *facebookId = #"yourFacebookId";
NSString *imageUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookId];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = [UIImage imageWithData:imageData];
});
});
}

how to change my synchronous to asynchronous call in Objective-C?

hi friend i am beginner for objective-c.i have slow response from server side due to synchronous call. i analysed in google the call may be asynchronous means the response speed will be high, but i don't know much about NSURLConnection and GCD. so please help me how to change my call asynchronous . see my code below`
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString* oldToken = [self deviceToken];
NSString *newToken = [[[[deviceToken description]stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"My token is: %#", newToken);
[self setDeviceToken:newToken];
if (![newToken isEqualToString:oldToken])
{
[self calur:newToken];
}
}
- (NSString*)deviceToken{
return [[NSUserDefaults standardUserDefaults] stringForKey:#"deviceid"];
}
- (void)setDeviceToken:(NSString*)token{
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"deviceid"];
}
//This function used to store a notification device id to our notification databae
-(void)calur:(NSString *)device
{
NSString *post =[NSString stringWithFormat:#"deviceId=%#",device];
NSString *hostStr = #"https://myserver.com/Ver_2_0/notification/check.php?";
NSError *error = nil;
NSString *nocon=[NSString stringWithContentsOfURL:[NSURL URLWithString:hostStr]encoding:NSUTF8StringEncoding error:&error];
if (nocon == nil)
{
NSLog(#"NO Connection");
}
else
{
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"hostStr=%#",hostStr);
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"dataURL=%#",dataURL);
// NSData *dataurl=dataURL;
if([serverOutput isEqualToString:#"Token Updated Successfully"])
{
NSLog(#"badge updated");
}
else
{
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"not registered");
}
[serverOutput release];
}
}`
if (nocon == nil)
{
NSLog(#"NO Connection");
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"hostStr=%#",hostStr);
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"dataURL=%#",dataURL);
// NSData *dataurl=dataURL;
if([serverOutput isEqualToString:#"Token Updated Successfully"])
{
NSLog(#"badge updated");
}
else
{
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"not registered");
}
[serverOutput release];
});
}
a little snippet:
#import "AFNetworking.h"
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:self.value, #"POSTvar", nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: [NSURL URLWithString:#"http://your.address"]];
NSURLRequest *request = [client requestWithMethod:#"POST" path:nil parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// do some with JSON
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
});
AFNetworking github

Upload Video to Vimeo in Objective C on iPhone

I am developing an app from which I want to upload Videos to Vimeo, Facebook and Youtube. Facebook and Youtube have pretty straightforward apis, Vimeo has a good developer documentation, but no Objective C framework. I have seen a couple of Apps which use Vimeo, so I was wondering if there is some kind of Framework out there I'm not aware of.
OK everybody. If you're still interested in how to upload a video to vimeo, here's the code. First you need to register an App with vimeo and obtain your secret and consumer key. Then you need to get the GTMOAuth framework from Google and possibly the SBJson framework. At the moment I unfortunately don't have the time to clean up the below code, but I thought this may be better than nothing for those, who need some help with vimeo. Essentially you authenticate with vimeo, get an upload ticket, upload the video with this ticket and then ad a title and some text.
The code below won't work out of the box, because there are a couple of view elements connected, but it should give you an understanding of what is happening.
#define VIMEO_SECRET #"1234567890"
#define VIMEO_CONSUMER_KEY #"1234567890"
#define VIMEO_BASE_URL #"http://vimeo.com/services/auth/"
#define VIMEO_REQUEST_TOKEN_URL #"http://vimeo.com/oauth/request_token"
#define VIMEO_AUTHORIZATION_URL #"http://vimeo.com/oauth/authorize?permission=write"
#define VIMEO_ACCESS_TOKEN_URL #"http://vimeo.com/oauth/access_token"
#import "MMVimeoUploaderVC.h"
#import "GTMOAuthAuthentication.h"
#import "GTMOAuthSignIn.h"
#import "GTMOAuthViewControllerTouch.h"
#import "JSON.h"
#interface MMVimeoUploaderVC ()
#property (retain) GTMOAuthAuthentication *signedAuth;
#property (retain) NSString *currentTicketID;
#property (retain) NSString *currentVideoID;
#property (assign) BOOL isUploading;
#property (retain) GTMHTTPFetcher *currentFetcher;
#end
#implementation MMVimeoUploaderVC
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
first = YES;
[GTMOAuthViewControllerTouch removeParamsFromKeychainForName:#"Vimeo"];
}
return self;
}
- (void)stopUpload {
if ( self.isUploading || self.currentFetcher ) {
[self.currentFetcher stopFetching];
}
}
- (void) setProgress:(float) progress {
// Connect to your views here
}
#pragma mark - handle error
- (void) handleErrorWithText:(NSString *) text {
//notify your views here
self.currentFetcher = nil;
self.isUploading = NO;
self.progressBar.alpha = 0;
self.uploadButton.alpha = 1;
}
#pragma mark - interface callbacks
//step one, authorize
- (void)startUpload {
if ( self.signedAuth ) {
//authentication present, start upload
} else {
//get vimeo authentication
NSURL *requestURL = [NSURL URLWithString:VIMEO_REQUEST_TOKEN_URL];
NSURL *accessURL = [NSURL URLWithString:VIMEO_ACCESS_TOKEN_URL];
NSURL *authorizeURL = [NSURL URLWithString:VIMEO_AUTHORIZATION_URL];
NSString *scope = #"";
GTMOAuthAuthentication *auth = [self vimeoAuth];
// set the callback URL to which the site should redirect, and for which
// the OAuth controller should look to determine when sign-in has
// finished or been canceled
//
// This URL does not need to be for an actual web page
[auth setCallback:#"http://www.....com/OAuthCallback"];
// Display the autentication view
GTMOAuthViewControllerTouch *viewController;
viewController = [[[GTMOAuthViewControllerTouch alloc] initWithScope:scope
language:nil
requestTokenURL:requestURL
authorizeTokenURL:authorizeURL
accessTokenURL:accessURL
authentication:auth
appServiceName:#"Vimeo"
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)] autorelease];
[[self navigationController] pushViewController:viewController
animated:YES];
}
}
//step two get upload ticket
- (void)viewController:(GTMOAuthViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuthAuthentication *)auth
error:(NSError *)error {
if (error != nil) {
[self handleErrorWithText:nil];
} else {
self.signedAuth = auth;
[self startUpload];
}
}
- (void) startUpload {
self.isUploading = YES;
NSURL *url = [NSURL URLWithString:#"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.upload.getQuota"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.signedAuth authorizeRequest:request];
GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request];
[myFetcher beginFetchWithDelegate:self
didFinishSelector:#selector(myFetcher:finishedWithData:error:)];
self.currentFetcher = myFetcher;
}
- (void) myFetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error {
if (error != nil) {
[self handleErrorWithText:nil];
NSLog(#"error %#", error);
} else {
NSString *info = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSDictionary *result = [info JSONValue];
//quota
int quota = [[result valueForKeyPath:#"user.upload_space.max"] intValue];
//get video file size
NSString *path;
path = #"local video path";
NSFileManager *manager = [NSFileManager defaultManager];
NSDictionary *attrs = [manager attributesOfItemAtPath:path error: NULL];
UInt32 size = [attrs fileSize];
if ( size > quota ) {
[self handleErrorWithText:#"Your Vimeo account quota is exceeded."];
return;
}
//lets assume we have enough quota
NSURL *url = [NSURL URLWithString:#"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.upload.getTicket&upload_method=streaming"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.signedAuth authorizeRequest:request];
GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request];
[myFetcher beginFetchWithDelegate:self
didFinishSelector:#selector(myFetcher2:finishedWithData:error:)];
self.currentFetcher = myFetcher;
}
}
- (void) myFetcher2:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error {
if (error != nil) {
[self handleErrorWithText:nil];
NSLog(#"error %#", error);
} else {
NSString *info = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSDictionary *result = [info JSONValue];
//fail here if neccessary TODO
NSString *urlString = [result valueForKeyPath:#"ticket.endpoint"];
self.currentTicketID = [result valueForKeyPath:#"ticket.id"];
if ( [self.currentTicketID length] == 0 || [urlString length] == 0) {
[self handleErrorWithText:nil];
return;
}
//get video file
// load the file data
NSString *path;
path = [MMMovieRenderer sharedRenderer].localVideoURL;
//get video file size
NSFileManager *manager = [NSFileManager defaultManager];
NSDictionary *attrs = [manager attributesOfItemAtPath:path error: NULL];
UInt32 size = [attrs fileSize];
//insert endpoint here
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"PUT"];
[request setValue:[NSString stringWithFormat:#"%i", size] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"video/mp4" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[NSData dataWithContentsOfFile:path]];
[self.signedAuth authorizeRequest:request];
GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request];
myFetcher.sentDataSelector = #selector(myFetcher:didSendBytes:totalBytesSent:totalBytesExpectedToSend:);
[myFetcher beginFetchWithDelegate:self
didFinishSelector:#selector(myFetcher3:finishedWithData:error:)];
self.currentFetcher = myFetcher;
}
}
- (void)myFetcher:(GTMHTTPFetcher *)fetcher
didSendBytes:(NSInteger)bytesSent
totalBytesSent:(NSInteger)totalBytesSent
totalBytesExpectedToSend:(NSInteger)totalBytesExpectedToSend {
NSLog(#"%i / %i", totalBytesSent, totalBytesExpectedToSend);
[self setProgress:(float)totalBytesSent / (float) totalBytesExpectedToSend];
self.uploadLabel.text = #"Uploading to Vimeo...";
}
- (void) myFetcher3:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error {
if (error != nil) {
[self handleErrorWithText:nil];
} else {
NSString *info = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//finalize upload
NSString *requestString = [NSString stringWithFormat:#"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.upload.complete&ticket_id=%#&filename=%#", self.currentTicketID, #"movie.mov"];
NSURL *url = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.signedAuth authorizeRequest:request];
GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request];
[myFetcher beginFetchWithDelegate:self
didFinishSelector:#selector(myFetcher4:finishedWithData:error:)];
self.currentFetcher = myFetcher;
}
}
- (void) myFetcher4:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error {
if (error != nil) {
[self handleErrorWithText:nil];
} else {
//finish upload
NSString *info = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSDictionary *result = [info JSONValue];
self.currentVideoID = [result valueForKeyPath:#"ticket.video_id"];
if ( [self.currentVideoID length] == 0 ) {
[self handleErrorWithText:nil];
return;
}
//set title
NSString *title = [MMMovieSettingsManager sharedManager].movieTitle;
title = [title stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString *requestString = [NSString stringWithFormat:#"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.setTitle&video_id=%#&title=%#", self.currentVideoID, title];
NSLog(#"%#", requestString);
NSURL *url = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.signedAuth authorizeRequest:request];
GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request];
[myFetcher beginFetchWithDelegate:self
didFinishSelector:#selector(myFetcher5:finishedWithData:error:)];
}
}
- (void) myFetcher5:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error {
if (error != nil) {
[self handleErrorWithText:nil];
NSLog(#"error %#", error);
} else {
//set description
NSString *desc = #"Video created with ... iPhone App.";
desc = [desc stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString *requestString = [NSString stringWithFormat:#"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.setDescription&video_id=%#&description=%#", self.currentVideoID, desc];
NSURL *url = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.signedAuth authorizeRequest:request];
GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request];
[myFetcher beginFetchWithDelegate:self
didFinishSelector:#selector(myFetcher6:finishedWithData:error:)];
}
}
- (void) myFetcher6:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error {
if (error != nil) {
[self handleErrorWithText:nil];
NSLog(#"error %#", error);
} else {
//done
//alert your views that the upload has been completed
}
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[self setProgress:0];
}
- (void) viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[GTMOAuthViewControllerTouch removeParamsFromKeychainForName:#"Vimeo"];
}
#pragma mark - oauth stuff
- (GTMOAuthAuthentication *)vimeoAuth {
NSString *myConsumerKey = VIMEO_CONSUMER_KEY; // pre-registered with service
NSString *myConsumerSecret = VIMEO_SECRET; // pre-assigned by service
GTMOAuthAuthentication *auth;
auth = [[[GTMOAuthAuthentication alloc] initWithSignatureMethod:kGTMOAuthSignatureMethodHMAC_SHA1
consumerKey:myConsumerKey
privateKey:myConsumerSecret] autorelease];
// setting the service name lets us inspect the auth object later to know
// what service it is for
auth.serviceProvider = #"Vimeo";
return auth;
}
#end
#import <Foundation/Foundation.h>
#protocol vimeodelagate;
#interface Vimeo_uploader : NSObject<NSURLSessionDelegate, NSURLSessionTaskDelegate>
#property(weak) id<vimeodelagate> delegate;
+(id)SharedManger;
-(void)pass_data_header:(NSData *)videoData;
- (void)Give_title_to_video:(NSString *)VIdeo_id With_name:(NSString *)name ;
#end
#protocol vimeodelagate <NSObject>
-(void)vimeouploader_succes:(NSString *)link methodName:(NSString *)methodName;
-(void)vimeouploader_progress:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalByte;
-(void)vimeouploader_error:(NSError *)error methodName:(NSString *)methodName;
#end
#define Aurtorizartion #"bearer 123456789" // replace 123456789 with your token, bearer text will be there
#define accept #"application/vnd.vimeo.*+json; version=3.2"
#import "Vimeo_uploader.h"
#implementation Vimeo_uploader
+(id)SharedManger{
static Vimeo_uploader *Vimeouploader = nil;
#synchronized (self) {
static dispatch_once_t oncetoken;
dispatch_once(&oncetoken, ^{
Vimeouploader = [[self alloc] init];
});
}
return Vimeouploader;
}
-(id)init{
if (self = [super init]) {
}
return self;
}
- (void)pass_data_header:(NSData *)videoData{
NSString *tmpUrl=[[NSString alloc]initWithFormat:#"https://api.vimeo.com/me/videos?type=streaming&redirect_url=&upgrade_to_1080=false"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:tmpUrl] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0];
[request setHTTPMethod:#"POST"];
[request setValue:Aurtorizartion forHTTPHeaderField:#"Authorization"];
[request setValue:accept forHTTPHeaderField:#"Accept"];//change this according to your need.
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &error];
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
if (!error) {
[self call_for_ticket:[json valueForKey:#"upload_link_secure"] complet_url:[json valueForKey:#"complete_uri"] videoData:videoData];
}else{
NSLog(#"RESPONSE--->%#",json);
}
}
- (void)call_for_ticket:(NSString *)upload_url complet_url:(NSString *)complet_uri videoData:(NSData *)videoData{
NSURLSessionConfiguration *configuration;
//configuration.timeoutIntervalForRequest = 5;
//configuration.timeoutIntervalForResource = 5;
configuration.HTTPMaximumConnectionsPerHost = 1;
configuration.allowsCellularAccess = YES;
// configuration.networkServiceType = NSURLNetworkServiceTypeBackground;
configuration.discretionary = NO;
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:upload_url];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:#"PUT"];
[urlRequest setTimeoutInterval:0];
[urlRequest setValue:Aurtorizartion forHTTPHeaderField:#"Authorization"];
[urlRequest setValue:accept forHTTPHeaderField:#"Accept"];
NSError *error;
NSString *str_lenth = [NSString stringWithFormat:#"%lu",(unsigned long)videoData.length];
NSDictionary *dict = #{#"str_lenth":str_lenth,
#"Content-Type":#"video/mp4"};
NSData *postData12 = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
[urlRequest setHTTPBody:postData12];
// [urlRequest setHTTPBody:videoData];
// You could try use uploadTaskWithRequest fromData
NSURLSessionUploadTask *taskUpload = [session uploadTaskWithRequest:urlRequest fromData:videoData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
if (!error && httpResp.statusCode == 200) {
[self call_complete_uri:complet_uri];
} else {
if([self.delegate respondsToSelector:#selector(vimeouploader_error:methodName:)]){
[self.delegate vimeouploader_error:error methodName:#"vimeo"];}
NSLog(#"ERROR: %# AND HTTPREST ERROR : %ld", error, (long)httpResp.statusCode);
}
}];
[taskUpload resume];
}
-(void)call_complete_uri:(NSString *)complettion_url{
NSString *str_url =[NSString stringWithFormat:#"https://api.vimeo.com%#",complettion_url];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:str_url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0];
[request setHTTPMethod:#"DELETE"];
[request setValue:Aurtorizartion forHTTPHeaderField:#"Authorization"];
[request setValue:accept forHTTPHeaderField:#"Accept"];
//change this according to your need.
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 201) {
NSDictionary *dict = [[NSDictionary alloc]initWithDictionary:[httpResponse allHeaderFields]];
if (dict) {
if([self.delegate respondsToSelector:#selector(vimeouploader_succes:methodName:)]){
// [self.delegate vimeouploader_succes:[dict valueForKey:#"Location"] methodName:#"vimeo"];
NSLog(#"sucesses");
NSString *str = [NSString stringWithFormat:#"title"];
[self Give_title_to_video:[dict valueForKey:#"Location"] With_name:str];
}else{
if([self.delegate respondsToSelector:#selector(vimeouploader_error:methodName:)]){
[self.delegate vimeouploader_error:error methodName:#"vimeo"];}
}
}
}else{
//9
if([self.delegate respondsToSelector:#selector(vimeouploader_error:methodName:)]){
[self.delegate vimeouploader_error:error methodName:#"vimeo"];}
NSLog(#"%#",error.localizedDescription);
}
}];
}
- (void)Give_title_to_video:(NSString *)VIdeo_id With_name:(NSString *)name {
NSString *tmpUrl=[[NSString alloc]initWithFormat:#"https://api.vimeo.com%#",VIdeo_id];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:tmpUrl] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0];
[request setHTTPMethod:#"PATCH"];
[request setValue:Aurtorizartion forHTTPHeaderField:#"Authorization"];
[request setValue:accept forHTTPHeaderField:#"Accept"];//change this according to your need.
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &error];
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
NSString *str_description = #"description";
NSDictionary *dict = #{#"name":name,
#"description":str_description,
#"review_link":#"false"
};
NSData *postData12 = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
[request setHTTPBody:postData12];
if (!error) {
NSLog(#"RESPONSE--->%#",json);
[self.delegate vimeouploader_succes:[json valueForKey:#"link"] methodName:#"vimeo"];
}else{
if([self.delegate respondsToSelector:#selector(vimeouploader_error:methodName:)]){
[self.delegate vimeouploader_error:error methodName:#"vimeo"];}
//NSLog(#"%#",error.localizedDescription);
NSLog(#"Give_title_to_video_error--->%#",error);
}
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
NSLog(#"didSendBodyData: %lld, totalBytesSent: %lld, totalBytesExpectedToSend: %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
if([self.delegate respondsToSelector:#selector(vimeouploader_progress:totalBytesExpectedToSend:)]){
[self.delegate vimeouploader_progress:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend];}
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
if (error == nil) {
NSLog(#"Task: %# upload complete", task);
} else {
NSLog(#"Task: %# upload with error: %#", task, [error localizedDescription]);
}
}
#end
The vimeo-Api is enough. Take a closer look to the vimeo-upload-api
The interface can be used in any language which is able to send network-data. You have to create some NSURLConnections and you have to set the HTTP-Body like in their examples.
I wrote AFNetworking Client for Vimeo API - https://github.com/m1entus/RWMViemoClient