将视频上传到 iPhone 上 Objective-C 中的 Vimeo

发布于 2024-12-07 03:33:58 字数 159 浏览 0 评论 0原文

我正在开发一个应用程序,我想将视频上传到 Vimeo、Facebook 和 YouTube。 Facebook 和 YouTube 有相当简单的 API,Vimeo 有很好的开发人员文档,但没有 Objective-C 框架。我见过几个使用 Vimeo 的应用程序,所以我想知道是否有某种我不知道的框架。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

情仇皆在手 2024-12-14 03:33:58

好吧大家。如果您仍然对如何将视频上传到 vimeo 感兴趣,请参阅以下代码。首先,您需要向 vimeo 注册应用程序并获取您的秘密和消费者密钥。然后您需要从 Google 获取 GTMOAuth 框架,也可能需要 SBJson 框架。不幸的是,目前我没有时间清理下面的代码,但我认为对于那些需要 vimeo 帮助的人来说,这可能比没有好。本质上,您使用 vimeo 进行身份验证,获取上传票证,使用此票证上传视频,然后广告标题和一些文本。

下面的代码不能开箱即用,因为有几个视图元素相连,但它应该让您了解正在发生的情况。

#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

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
野の 2024-12-14 03:33:58
#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
#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
灰色世界里的红玫瑰 2024-12-14 03:33:58

vimeo-Api 就足够了。仔细看看 vimeo-upload-api

该界面可以用任何语言使用能够发送网络数据。您必须创建一些 NSURLConnections 并且必须像示例中那样设置 HTTP-Body。

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.

眼眸印温柔 2024-12-14 03:33:58

我为 Vimeo API 编写了 AFNetworking 客户端 - https://github.com/m1entus/RWMViemoClient

I wrote AFNetworking Client for Vimeo API - https://github.com/m1entus/RWMViemoClient

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文