2013-04-25 1 views
4

전 iOS를 처음 사용합니다. Dropbox에서 /로 파일을 업로드/다운로드하려면 어떻게해야합니까? 내 앱에 드롭 박스 애플리케이션을 통합했지만 파일을 업로드/다운로드 할 수 없었습니다.xcode를 사용하여 드롭 박스에서 파일을 업로드/다운로드하는 방법

이 내 업로드 코드 : 다운로드 이것은

- (NSString *)getDocumentPath 
{ 
    NSMutableData * pdfData = [NSMutableData data]; 
    UIGraphicsBeginPDFContextToData(pdfData, self.view.bounds, nil); 
    UIGraphicsBeginPDFPage(); 
    CGContextRef pdfContext = UIGraphicsGetCurrentContext(); 
    [self.view.layer renderInContext:pdfContext]; 
    UIGraphicsEndPDFContext(); 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"vani.doc"]; 

    [pdfData writeToFile:path atomically:YES]; 

    return path; 

} 

- (IBAction)upload:(id)sender { 

    NSString *path = [self getDocumentPath]; 

    NSString * local = [path lastPathComponent]; 

    NSString *destDir = @"/Plist Folder/vani.doc"; 

    [restClient uploadFile:local toPath:destDir withParentRev:nil fromPath:path]; 

:

restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]]; 
    restClient.delegate = self; 
    NSString *fileName = [NSString stringWithFormat:@"/vani.doc"]; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                 NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString* path2 = [documentsDirectory stringByAppendingString: 
         [NSString stringWithFormat:@"%@", fileName]]; 
    //NSLog(@"%@", path2); 

    [restClient loadFile:fileName intoPath:path2]; 

저를 도와주세요. 나 엄청 혼란스러워.

+2

그리고 무엇이 문제입니까? 혼란의 원인? 오류 기록 ? –

+0

.. 실제로 Dropbox 응용 프로그램에 문제가 있습니다. –

+0

iam이 파일을 업로드하고 다운로드하려고 시도 중입니다 ... bt i couldn .. –

답변

5

이 경우에 도움을 드리겠습니다. Dropbox에 대한 래퍼 클래스를 만들었습니다. 아래 코드는 내 프로젝트에서 사용되었습니다. ARC를 지원하지 않습니다. DropBoxManager 헤더 및 구현 파일 만들기 초보자에게는이 방법이 너무 어려울 수 있지만 전체 대답을 읽고 단계별로 따라하십시오. 문제가 생기면 알려주십시오. 도와 드리겠습니다.

코드 DropBoxManager.h

#import <Foundation/Foundation.h> 
#import <DropboxSDK/DropboxSDK.h> 

#define kDropbox_AppKey @"" // Provide your key here 
#define kDropbox_AppSecret @"" // Provide your secret key here 
#define kDropbox_RootFolder kDBRootDropbox //Decide level access like root or app 

@protocol DropBoxDelegate; 

typedef enum 
{ 
    DropBoxTypeStatusNone = 0, 
    DropBoxGetAccountInfo = 1, 
    DropBoxGetFolderList = 2, 
    DropBoxCreateFolder = 3, 
    DropBoxUploadFile = 4 
} DropBoxPostType; 

@interface DropboxManager : NSObject <DBRestClientDelegate,DBSessionDelegate,UIAlertViewDelegate> 
{ 
    UIViewController<DropBoxDelegate> *apiCallDelegate; 

    DBSession *objDBSession; 
    NSString *relinkUserId; 
    DBRestClient *objRestClient; 

    DropBoxPostType currentPostType; 

    NSString *strFileName; 
    NSString *strFilePath; 
    NSString *strDestDirectory; 
    NSString *strFolderCreate; 
    NSString *strFolderToList; 
} 

@property (nonatomic,retain) DBSession *objDBSession; 
@property (nonatomic,retain) NSString *relinkUserId; 

@property (nonatomic,assign) UIViewController<DropBoxDelegate> *apiCallDelegate; 

@property (nonatomic,retain) DBRestClient *objRestClient; 

@property (nonatomic,assign) DropBoxPostType currentPostType; 

@property (nonatomic,retain) NSString *strFileName; 
@property (nonatomic,retain) NSString *strFilePath; 
@property (nonatomic,retain) NSString *strDestDirectory; 

@property (nonatomic,retain) NSString *strFolderCreate; 

@property (nonatomic,retain) NSString *strFolderToList; 

//Singleton 
+(id)dropBoxManager; 

//Initialize dropbox 
-(void)initDropbox; 

//Authentication Verification 
-(BOOL)handledURL:(NSURL*)url; 
-(void)dropboxDidLogin; 
-(void)dropboxDidNotLogin; 

//Upload file 
-(void)uploadFile; 

//Download File 
-(void)downlaodFileFromSourcePath:(NSString*)pstrSourcePath destinationPath:(NSString*)toPath; 

//Create Folder 
-(void)createFolder; 

//Get Account Information 
-(void)loginToDropbox; 
-(void)logoutFromDropbox; 
-(BOOL)isLoggedIn; 

//List Folders 
-(void)listFolders; 

@end 

@protocol DropBoxDelegate <NSObject> 

@optional 

- (void)finishedLogin:(NSMutableDictionary*)userInfo; 
- (void)failedToLogin:(NSString*)withMessage; 

- (void)finishedCreateFolder; 
- (void)failedToCreateFolder:(NSString*)withMessage; 

- (void)finishedUploadFile; 
- (void)failedToUploadFile:(NSString*)withMessage; 

- (void)finishedDownloadFile; 
- (void)failedToDownloadFile:(NSString*)withMessage; 

- (void)getFolderContentFinished:(DBMetadata*)metadata; 
- (void)getFolderContentFailed:(NSString*)withMessage; 

@end 

코드에 대한 DropBoxManager.m

#import "DropboxManager.h" 

@implementation DropboxManager 

@synthesize objDBSession,relinkUserId,apiCallDelegate; 
@synthesize objRestClient; 
@synthesize currentPostType; 

@synthesize strFileName; 
@synthesize strFilePath; 
@synthesize strDestDirectory; 

@synthesize strFolderCreate; 

@synthesize strFolderToList; 

static DropboxManager *singletonManager = nil; 

+(id)dropBoxManager 
{ 
    if(!singletonManager) 
     singletonManager = [[DropboxManager alloc] init]; 

    return singletonManager; 
} 

-(void)initDropbox 
{ 
    DBSession* session = [[DBSession alloc] initWithAppKey:kDropbox_AppKey appSecret:kDropbox_AppSecret root:kDropbox_RootFolder]; 
    session.delegate = self; 
    [DBSession setSharedSession:session]; 
    [session release]; 

    if([[DBSession sharedSession] isLinked] && objRestClient == nil) 
    {  
     self.objRestClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]]; 
     self.objRestClient.delegate = self; 
    } 
} 

-(void)checkForLink 
{ 
    if(![[DBSession sharedSession] isLinked]) 
     [[DBSession sharedSession] linkFromController:apiCallDelegate]; 
} 

-(BOOL)handledURL:(NSURL*)url 
{ 
    BOOL isLinked=NO; 
    if ([[DBSession sharedSession] handleOpenURL:url]) 
    { 

     if([[DBSession sharedSession] isLinked]) 
     { 
      isLinked=YES; 
      [self dropboxDidLogin]; 
     } 
     else 
     { 
      isLinked = NO; 
      [self dropboxDidNotLogin]; 
     } 
    } 
    return isLinked; 
} 

#pragma mark - 
#pragma mark Handle login 

-(void)dropboxDidLogin 
{ 
    NSLog(@"Logged in"); 

    if([[DBSession sharedSession] isLinked] && self.objRestClient == nil) 
    {  
     self.objRestClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]]; 
     self.objRestClient.delegate = self; 
    } 

    switch(currentPostType) 
    { 
     case DropBoxTypeStatusNone: 

      break; 

     case DropBoxGetAccountInfo: 
      [self loginToDropbox]; 
      break; 

     case DropBoxGetFolderList: 
      [self listFolders]; 
      break; 

     case DropBoxCreateFolder: 
      [self createFolder]; 
      break; 

     case DropBoxUploadFile: 
      [self uploadFile]; 
      break;   
    } 

    //[(MainViewController*)apiCallDelegate setLoginStatus]; 
} 

-(void)dropboxDidNotLogin 
{ 
    NSLog(@"Not Logged in"); 
    switch(currentPostType) 
    { 
     case DropBoxTypeStatusNone: 

      break; 

     case DropBoxUploadFile: 
      if([self.apiCallDelegate respondsToSelector:@selector(failedToUploadFile:)]) 
       [self.apiCallDelegate failedToUploadFile:@"Problem connecting dropbox. Please try again later."]; 
      break; 

     case DropBoxGetFolderList: 

      break; 

     case DropBoxCreateFolder: 

      break; 

     case DropBoxGetAccountInfo: 

      break; 
    } 
} 

#pragma mark - 
#pragma mark DBSessionDelegate methods 

- (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session userId:(NSString *)userId 
{ 
    relinkUserId = [userId retain]; 
    [[[[UIAlertView alloc] initWithTitle:@"Dropbox Session Ended" message:@"Do you want to relink?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Relink", nil] autorelease] show]; 
} 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)index 
{ 
    if (index != alertView.cancelButtonIndex) 
     [[DBSession sharedSession] linkUserId:relinkUserId fromController:apiCallDelegate]; 

    [relinkUserId release]; 
    relinkUserId = nil; 
} 

#pragma mark - 
#pragma mark Fileupload 

-(void)uploadFile 
{ 
    if([[DBSession sharedSession] isLinked]) 
     [self.objRestClient uploadFile:strFileName toPath:strDestDirectory withParentRev:nil fromPath:strFilePath]; 
    else 
     [self checkForLink]; 
} 

-(void)downlaodFileFromSourcePath:(NSString*)pstrSourcePath destinationPath:(NSString*)toPath 
{ 
    if([[DBSession sharedSession] isLinked]) 
     [self.objRestClient loadFile:pstrSourcePath intoPath:toPath]; 
    else 
     [self checkForLink]; 
} 

- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath from:(NSString*)srcPath metadata:(DBMetadata*)metadata 
{ 
    if([self.apiCallDelegate respondsToSelector:@selector(finishedUploadeFile)]) 
     [self.apiCallDelegate finishedUploadFile]; 

    NSLog(@"File uploaded successfully to path: %@", metadata.path); 
} 

- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)destPath contentType:(NSString*)contentType 
{ 
    if([self.apiCallDelegate respondsToSelector:@selector(finishedDownloadFile)]) 
     [self.apiCallDelegate finishedDownloadFile]; 
} 

-(void)restClient:(DBRestClient *)client loadFileFailedWithError:(NSError *)error 
{ 
    if([self.apiCallDelegate respondsToSelector:@selector(failedToDownloadFile:)]) 
     [self.apiCallDelegate failedToDownloadFile:[error description]]; 
} 

- (void)restClient:(DBRestClient*)client uploadFileFailedWithError:(NSError*)error 
{ 
    if([self.apiCallDelegate respondsToSelector:@selector(failedToUploadFile:)]) 
     [self.apiCallDelegate failedToUploadFile:[error description]]; 

    NSLog(@"File upload failed with error - %@", error); 
} 

#pragma mark - 
#pragma mark Create Folder 

-(void)createFolder 
{ 
    if([[DBSession sharedSession] isLinked]) 
     [self.objRestClient createFolder:strFolderCreate]; 
    else 
     [self checkForLink]; 
} 

- (void)restClient:(DBRestClient*)client createdFolder:(DBMetadata*)folder 
{ 
    if([self.apiCallDelegate respondsToSelector:@selector(finishedCreateFolder)]) 
     [self.apiCallDelegate finishedCreateFolder]; 

    NSLog(@"Folder created successfully to path: %@", folder.path); 
} 

- (void)restClient:(DBRestClient*)client createFolderFailedWithError:(NSError*)error 
{ 
    if([self.apiCallDelegate respondsToSelector:@selector(failedToCreateFolder:)]) 
     [self.apiCallDelegate failedToCreateFolder:[error description]]; 

    NSLog(@"Folder create failed with error - %@", error); 
} 

#pragma mark - 
#pragma mark Load account information 

-(void)loginToDropbox 
{ 
    if([[DBSession sharedSession] isLinked]) 
     [self.objRestClient loadAccountInfo]; 
    else 
     [self checkForLink]; 
} 

- (void)restClient:(DBRestClient*)client loadedAccountInfo:(DBAccountInfo*)info 
{ 
    if([self.apiCallDelegate respondsToSelector:@selector(finishedLogin:)]) 
    { 
     NSMutableDictionary *userInfo = [[[NSMutableDictionary alloc] init] autorelease]; 
     [userInfo setObject:info.displayName forKey:@"UserName"]; 
     [userInfo setObject:info.userId forKey:@"UserID"]; 
     [userInfo setObject:info.referralLink forKey:@"RefferelLink"]; 
     [self.apiCallDelegate finishedLogin:userInfo]; 
    } 

    NSLog(@"Got Information: %@", info.displayName); 
} 

- (void)restClient:(DBRestClient*)client loadAccountInfoFailedWithError:(NSError*)error 
{ 
    if([self.apiCallDelegate respondsToSelector:@selector(failedToLogin:)]) 
     [self.apiCallDelegate failedToLogin:[error description]]; 

    NSLog(@"Failed to get account information with error - %@", error); 
} 

#pragma mark - 
#pragma mark Logout 

-(void)logoutFromDropbox 
{ 
    [[DBSession sharedSession] unlinkAll]; 
    [self.objRestClient release]; 
} 

#pragma mark - 
#pragma mark Check for login 

-(BOOL)isLoggedIn 
{ 
    return [[DBSession sharedSession] isLinked] ? YES : NO; 
} 

#pragma mark - 
#pragma mark Load Folder list 

-(void)listFolders 
{ 
    NSLog(@"Here-->%@",self.strFolderToList); 
    if([[DBSession sharedSession] isLinked]) 
     [self.objRestClient loadMetadata:self.strFolderToList]; 
    else 
     [self checkForLink];  
} 

- (void)restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata 
{ 
    if (metadata.isDirectory) 
    { 
     NSLog(@"Folder '%@' contains:", metadata.contents); 
     for (DBMetadata *file in metadata.contents) 
     { 
      NSLog(@"\t%@", file); 
     } 

     if([apiCallDelegate respondsToSelector:@selector(getFolderContentFinished:)]) 
      [apiCallDelegate getFolderContentFinished:metadata]; 
    } 
    NSLog(@"Folder list success: %@", metadata.path); 

} 

- (void)restClient:(DBRestClient*)client metadataUnchangedAtPath:(NSString*)path 
{ 

} 

- (void)restClient:(DBRestClient*)client loadMetadataFailedWithError:(NSError*)error 
{ 
    NSLog(@"Load meta data failed with error - %@", error); 

    if([apiCallDelegate respondsToSelector:@selector(getFolderContentFailed:)]) 
     [apiCallDelegate getFolderContentFailed:[error localizedDescription]]; 
} 

일예 사용 헤더 파일

//Your view controller Header file. 
#import <UIKit/UIKit.h> 
#import "DropboxManager.h" 

@interface YourViewController : UIViewController <DropBoxDelegate> 
{ 
    DropboxManager *objManager; 
} 

@property (nonatomic,assign) DropboxManager *objManager; 


-(IBAction)btnUploadFileTapped:(id)sender; 

@end 

예 : 당신은 ARC 이외의 오류가 모든 곳에서 사용 구현 파일은

#import "YourViewController.h" 

@implementation YourViewController 
@synthesize objManager; 

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad { 
    [super viewDidLoad]; 

    objManager = [DropboxManager dropBoxManager]; 
    objManager.apiCallDelegate =self; 
    [objManager initDropbox]; 
} 

-(IBAction)btnUploadFileTapped:(id)sender 
{ 
    objManager.currentPostType = DropBoxUploadFile; 
    objManager.strFileName = @"YourFileName"; 
    objManager.strFilePath = @"YourFilePath"; 
    objManager.strDestDirectory = @"/"; 
    [objManager uploadFile]; 
} 

#pragma mark - 
#pragma mark File upload delegate 

- (void)finishedUploadFile 
{ 
    NSLog(@"Uploaded successfully."); 
} 

- (void)failedToUploadFile:(NSString*)withMessage 
{ 
    NSLog(@"Failed to upload error is %@",withMessage); 
} 

@end 
+0

Janak Nirmal에게 회신 해 주셔서 감사합니다. –

+0

예. 나는 초급자입니다 .. 이해하기가 매우 어렵습니다. 설명해 주시겠습니까? –

+0

DropBoxManager.h 및 DropBoxManager.m 파일을 만들어야합니다. 위의 코드 복사 나는 그 파일들을주고 받았다. 이제 'YourViewController'라는 이름으로 새 컨트롤러를 만들고 위의 헤더와 구현 파일 코드를 대체하십시오. 파일 이름과 파일 경로에 대해 btnUploadFileTapped 메서드를 변경하고 xib 파일의 단추 중 하나와 바인딩해야합니다. 따라하고 버튼을 클릭하십시오. –

0

그냥

import UIKit/UIKit.h 

추가 할 수 있습니다.