how can I use NSURLConnection Asynchronously? - objective-c

I am using this code to load data to my App, can you tell me how can I make this asynchronously?
NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
if (connection)
{
NSLog(#"NSURLConnection connection==true");
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&response error:&err];
self.news =[NSJSONSerialization JSONObjectWithData:responseData options:nil error:nil];
NSLog(#"responseData: %#", self.news);
}
else
{
NSLog(#"NSURLConnection connection==false");
};

I think you should be bothered reading the documentation. There's a sendAsynchronousRequest:queue:completionHandler: method.

Create the connection with initWithRequest:delegate:startImmediately:, set yourself as its delegate and implement the delegate methods.

Block code is your friend. I have created a class which does this for you
Objective-C Block code. Create this class here
Interface class
#import <Foundation/Foundation.h>
#import "WebCall.h"
#interface WebCall : NSObject
{
void(^webCallDidFinish)(NSString *response);
}
#property (nonatomic, retain) NSMutableData *responseData;
-(void)setWebCallDidFinish:(void (^)(NSString *))wcdf;
-(void)webServiceCall :(NSString *)sURL_p : (NSMutableArray *)valueList_p : (NSMutableArray *)keyList_p;
#end
Implementation class
#import "WebCall.h"
#import "AppDelegate.h"
#implementation WebCall
#synthesize responseData;
-(void)setWebCallDidFinish:(void (^)(NSString *))wcdf
{
webCallDidFinish = [wcdf copy];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int responseStatusCode = [httpResponse statusCode];
NSLog(#"Response Code = %i", responseStatusCode);
if(responseStatusCode < 200 || responseStatusCode > 300)
{
webCallDidFinish(#"failure");
}
[responseData setLength:0];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"WebCall Error: %#", error);
webCallDidFinish(#"failure");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
response = [response stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
webCallDidFinish(response);
}
-(void)webServiceCall :(NSString *)sURL_p : (NSMutableArray *)valueList_p : (NSMutableArray *)keyList_p
{
NSMutableString *sPost = [[NSMutableString alloc] init];
//If any variables need passed in - append them to the POST
//E.g. if keyList object is username and valueList object is adam will append like
//http://test.jsp?username=adam
if([valueList_p count] > 0)
{
for(int i = 0; i < [valueList_p count]; i++)
{
if(i == 0)
{
[sPost appendFormat:#"%#=%#", [valueList_p objectAtIndex:i],[keyList_p objectAtIndex:i]];
}
else
{
[sPost appendFormat:#"&%#=%#", [valueList_p objectAtIndex:i], [keyList_p objectAtIndex:i]];
}
}
}
NSData * postData = [sPost dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSURL * url = [NSURL URLWithString:sURL_p];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
if (theConnection)
{
self.responseData = [NSMutableData data];
}
}
#end
Then you to make this web call, you call it like this
WebCall *webCall = [[WebCall alloc] init];
[webCall setWebCallDidFinish:^(NSString *response){
//This method is called as as soon as the web call is finished
NSString *trimmedString = [response stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([trimmedString rangeOfString:#"failure"].location == NSNotFound)
{
//Successful web call
}
else
{
//If the webcall failed due to an error
}
}];
//Make web call here
[webCall webServiceCall:#"http://www.bbc.co.uk/" :nil :nil];
See the setWebCallDidFinish method, it will not be called until the webcall has finished.
Hope that helps!!

Here is some code which I am using in my app:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:yourURL]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Error loading data from %#. Error Userinfo: %#",yourURL, [error userInfo]);
} else {
NSDictionary *dataFromServer = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
contentAsString = [[[dataFromServer objectForKey:#"page"] objectForKey:#"content"] stripHtml];
completionHandler(contentAsString);
}];
fyi: stripHTML is a NSString Category to remove HTML tags from JSON --> Found it Here
you can call your content in your class like that:
[yourClass getDataWithcompletionHandler:^(NSString *content) {
yourObject.content = content;
[yourClass saveManagedObjectContext];
}];
if you implement it once, you won't want to use synchronous connection again...

Check this out: HTTPCachedController
It will help you send POST and GET requests, while it will cache the response and after that it will return the cached data when no internet connection is available.
HTTPCachedController *ctrl = [[[HTTPCachedController alloc] initWithRequestType:1 andDelegate:self] autorelease];
[ctrl getRequestToURL:#"https://api.github.com/orgs/twitter/repos?page=1&per_page=10"];
You will get notified when the data are fetched through a delegate method:
-(void)connectionFinishedWithData:(NSString*)data andRequestType:(int)reqType

Related

Objective-C how to convert nsdata from web service to nsarray

How do i convert id to an array?
I have an apple app that talks to a server.
Issue i have is the app returns the data in the form of id however i need to convert this to an array as the actual returned data looks like the following.
[["30","2",1],["15","67",1],["30","4",1]]
It is actually the output from a mysql server
The actual app code looks like the following
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"blah blah"]];
NSURL_Layer * connection = [[NSURL_Layer alloc]initWithRequest:request];
[connection setCompletitionBlock:^(id obj, NSError *err) {
if (!err) {
//Need to convert the id to nsarray here, dunno how
} else {
//There was an error
}
}];
[connection start];
The NSURL.h
-(id)initWithRequest:(NSURLRequest *)req;
#property (nonatomic,copy)NSURLConnection * internalConnection;
#property (nonatomic,copy)NSURLRequest *request;
#property (nonatomic,copy)void (^completitionBlock) (id obj, NSError * err);
-(void)start;
NSURL.m
-(id)initWithRequest:(NSURLRequest *)req {
self = [super init];
if (self) {
[self setRequest:req];
}
return self;
}
-(void)start {
container = [[NSMutableData alloc]init];
internalConnection = [[NSURLConnection alloc]initWithRequest:[self request] delegate:self startImmediately:YES];
if(!sharedConnectionList)
sharedConnectionList = [[NSMutableArray alloc] init];
[sharedConnectionList addObject:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[container appendData:data];
}
//If finish, return the data and the error nil
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
if([self completitionBlock])
[self completitionBlock](container,nil);
[sharedConnectionList removeObject:self];
}
//If fail, return nil and an error
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if([self completitionBlock])
[self completitionBlock](nil,error);
[sharedConnectionList removeObject:self];
}
Update:
i have added
NSURL_Layer * connection = [[NSURL_Layer alloc]initWithRequest:request];
[connection setCompletitionBlock:^(id obj, NSError *err) {
if (!err) {
NSError* error;
NSArray* array = [NSJSONSerialization JSONObjectWithData:obj options:NSJSONReadingAllowFragments error:&error];
} else {
//There was an error
}
}];
[connection start];
but returns error
error NSError * domain: #"NSCocoaErrorDomain" - code: 3840
_userInfo NSDictionary * 1 key/value pair
[0] (null) #"NSDebugDescription" : #"Invalid value around character 0."
Update: I put
NSLog(#"Data as string:%#", [[NSString alloc]initWithData:obj encoding:NSUTF8StringEncoding]);
which gave me a strange feedback. As a result i looked at my url request full code is below.
NSString *post = [NSString stringWithFormat:#"unique_id=%#&unique_password=%#",ServerUniqueID,ServerPassword];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"blah blah"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURL_Layer * connection = [[NSURL_Layer alloc]initWithRequest:request];
[connection setCompletitionBlock:^(id obj, NSError *err) {
if (!err)
{
NSError* error;
NSArray* array = [NSJSONSerialization JSONObjectWithData:[NSData dataWithData: obj] options:NSJSONReadingAllowFragments error:&error];
NSLog(#"Data as string:%#", [[NSString alloc]initWithData:obj encoding:NSUTF8StringEncoding]);
int temp = array.count;
}
else
{
//There was an error
}
}];
[connection start];
if i remove
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
it works
if its in it dosn't so i have a whole new issue to look into.
you save the bytes into a container variable, alas the id infact NSData
(note id is just a 'wildcard pointer' that means ANY objC object)
so your id is NSData and from what you show it seems to be 3 json arrays... but no real JSON... (["30","2",1]["15","67",1]["30","4",1] isn't anything)
EITHER make the server send you JSON and THAT you can parse into a dictionary/array using NSJSONSerialization
OR write a custom separator to convert the data

Video not getting downloaded

I need to download this video http://studiokicks.com/xtr/basic/1.mov The video is not getting downloaded when I use the following code:
NSURL *requestURL = [NSURL URLWithString:itemURL];
NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];
NSData *data = [NSData dataWithContentsOfURL:requestURL];
NSLog(#"data - %d",[data length]);
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse");
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ((([httpResponse statusCode]/100) == 2)) {
returnData = [NSMutableData data];
}
else
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject: NSLocalizedString(#"HTTP Error", #"Error message displayed when receving a connection error.")forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:#"HTTP" code:[httpResponse statusCode] userInfo:userInfo];
NSLog(#"%#",error);
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[returnData appendData:data];
// Build an array from the dictionary for easy access to each entry
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection1
{
NSString *filePath = [VIDEOPATH stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mov",videoName]];
BOOL success = [returnData writeToFile:filePath atomically:YES];
NSLog(#"successfully saved - %d",success);
}
You need to set a member self.data of type NSMutableData.
Before starting loading the NSURLConnection, initialize: self.data = [NSMutableData new].
In the connectionDidReceiveData method do: [self.data appendData:data].
And in the connectionDidFinishLoading you can view the data.

iOs receivedData from NSURLConnection is nil

I was wondering if anyone could point out why I'm not able to capture a web reply. My NSLog shows that my [NSMutableData receivedData] has a length of 0 the entire run of the connection. The script that I hit when I click my login button returns a string. My NSLog result is pasted below, and after that I've pasted both the .h and .m files that I have.
NSLog Result
2012-11-28 23:35:22.083 [12548:c07] Clicked on button_login
2012-11-28 23:35:22.090 [12548:c07] theConnection is succesful
2012-11-28 23:35:22.289 [12548:c07] didReceiveResponse
2012-11-28 23:35:22.290 [12548:c07] didReceiveData
2012-11-28 23:35:22.290 [12548:c07] 0
2012-11-28 23:35:22.290 [12548:c07] connectionDidFinishLoading
2012-11-28 23:35:22.290 [12548:c07] 0
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
// Create an Action for the button.
- (IBAction)button_login:(id)sender;
// Add property declaration.
#property (nonatomic,assign) NSMutableData *receivedData;
#end
ViewController.m
#import ViewController.h
#interface ViewController ()
#end
#implementation ViewController
#synthesize receivedData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse");
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"didReceiveData");
[receivedData appendData:data];
NSLog(#"%d",[receivedData length]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"%d",[receivedData length]);
}
- (IBAction)button_login:(id)sender {
NSLog(#"Clicked on button_login");
NSString *loginScriptURL = [NSString stringWithFormat:#"http://www.website.com/app/scripts/login.php?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:loginScriptURL]];
NSString *postString = [NSString stringWithFormat:#"&paramUsername=user&paramPassword=pass"];
NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:postData];
// Create the actual connection using the request.
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
// Capture the response
if (theConnection) {
NSLog(#"theConnection is succesful");
} else {
NSLog(#"theConnection failed");
}
}
#end
The issue is you are not initializing the receivedData instance. Just change your property like:
#property (nonatomic, retain) NSMutableData *receivedData;
And change the methods like:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse");
[self.receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"didReceiveData");
[self.receivedData appendData:data];
NSLog(#"%d",[receivedData length]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading");
NSLog(#"%d",[receivedData length]);
}
- (IBAction)button_login:(id)sender
{
NSLog(#"Clicked on button_login");
NSString *loginScriptURL = [NSString stringWithFormat:#"http://www.website.com/app/scripts/login.php?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:loginScriptURL]];
NSString *postString = [NSString stringWithFormat:#"&paramUsername=user&paramPassword=pass"];
NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:postData];
// Create the actual connection using the request.
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
// Capture the response
if (theConnection)
{
NSLog(#"theConnection is succesful");
self.receivedData = [NSMutableData data];
} else
{
NSLog(#"theConnection failed");
}
}
Please try "%i" instead of %d in nslog
You can try the following code May be help you.
- (IBAction)button_login:(id)sender {
NSLog(#"Clicked on button_login");
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:#"user" forKey:#"Username"];
[dictionnary setObject:#"pass" forKey:#"Password"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = #"Sample URL";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
NSLog(#"%#", responseString);
}
if it is a GET Request then, can you try link : /login.php?username=admin&password=1212‌​3
- (IBAction)button_login:(id)sender {
NSLog(#"Clicked on button_login");
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"/login.php?username=adm‌​in&password=1212‌​3"]];
// Perform request and get JSON as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"response=%#",response );
}
and use this code.

How to validate Username and password with Webserver values in I phone application

I am developing view based application.I have login page when we click on Login button it should check entered values with webserver values and it should display vali or invalid.I have wriiten code in this way it is executing successfully i am getting the result in this way
<!DOCTYPE html PUbLIC" -//W3C//DTD XHTML 1.0 Strict....
What i need to change in below code to comapre with server values..can any one help me regarding this please...
-(IBAction)buttonClick:(id)sender
{
NSString* username = nameInput.text;
NSString* pass = passInput.text;
if([nameInput.text isEqualToString:#"" ]|| [passInput.text isEqualToString:#""])
{
greeting.text = #"Input Your Value";
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
return;
}
NSString *post =
[[NSString alloc] initWithFormat:#"uname=%#&pwd=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"https://108.16.210.28/Account/LogOn"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
}
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
nameInput.text = nil;
passInput.text = nil;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(loginStatus);
greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
}
- (void)dealloc {
[super dealloc];
}
#end
Use statusCode to see the login state.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
if([response isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *theResponse = (NSHTTPURLResponse*)response;
NSInteger theStatusCode = [theResponse statusCode];
}
}
you have to parse the data.If it is in the form of XML data then you have to parse the element (like valid) in the didfoundcharacters.If it is valid then make a variable like BOOL confirm = NO;Modify this in the didfoundcharacters.if (confirm) then give access further

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