34
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Evernote ios sdkでテキストと画像投げるだけの最も簡単な例

Last updated at Posted at 2012-09-11

sample code of posting (uploading) text and image to Evernote from ios app

Evernoteに認証してテキストと画像をアップロードするのに必要な処理。
まだ認証してなかったらモーダルなWebViewの認証画面を呼び出して認証成功後に再試行する。
ここまでを書き下したサンプルコードがなかったので書いてみた。

EvernoteSDKは一応これをコピペするだけでひと通りちゃんと認証して投稿もできる。
別途設定画面を追加したりデリゲートがいくつも必要だったりはしないので、アプリに組み込むのはFacebookSDKよりも楽かもしれない。
でもノートオブジェクトや画像リソースを作ったりなど、データの構築処理するのが面倒すぎるのが残念。。

追記:md5ハッシュ計算するためにはSecurity.frameworkを追加する必要がある

# import "CommonCrypto/CommonDigest.h"
# import "EvernoteSDK.h"
- (void)sendEvernote:(NSString *)sendText withUIImage:(UIImage *)sendImage
{
    NSString *EVERNOTE_HOST = @"sandbox.evernote.com";
    NSString *CONSUMER_KEY = @"your_key";
    NSString *CONSUMER_SECRET = @"qwaserdftg123";
    [EvernoteSession setSharedSessionHost:EVERNOTE_HOST 
                              consumerKey:CONSUMER_KEY 
                           consumerSecret:CONSUMER_SECRET];
    EvernoteSession *session = [EvernoteSession sharedSession];
    if (session.isAuthenticated) {
        // sendTextの改行コード\nを<br/>にする&一行目をタイトルにする
        NSArray *textLines = [sendText componentsSeparatedByString:@"\n"];
        NSString *title = [[NSString alloc] initWithFormat:@"%@", [textLines objectAtIndex:0]];
        NSMutableString *contentBody = [NSMutableString string];
        for (NSString* line in textLines) {
            [contentBody appendFormat:@"%@<br/>", line];
        }
        NSArray *tagNames = [NSArray arrayWithObject:@"hoge"];
        [self evernoteCreateNote:title withUIImage:sendImage withContentBody:contentBody withTagNames:tagNames];
    } else {
        // 認証 EvernoteSessionクラスが勝手にモーダルなWebViewを作ってEvernoteのサイトで認証、完了したら発行されるTokenを勝手にどこかに保存するところまでやってくれる
        [session authenticateWithViewController:view
                              completionHandler:^(NSError *error) {
            if (error || !session.isAuthenticated) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
                                                                message:@"Could not authenticate" 
                                                               delegate:nil 
                                                      cancelButtonTitle:@"OK" 
                                                      otherButtonTitles:nil];
                [alert show];
            } else {
                // 投稿再試行
                [self sendEvernote:sendText withUIImage:sendImage];
            }
        }];
    }
}

// 認証済みアカウントのデフォルトのNotebookに新たなNoteを追加するためのメソッド
- (void)evernoteCreateNote:(NSString *)title
               withUIImage:(UIImage *)sendImage
           withContentBody:(NSMutableString *)contentBody
              withTagNames:(NSArray *)tagNames 
{
    // create image hash and resource from sendImage
    NSData* sendData = [[NSData alloc] initWithData:UIImagePNGRepresentation(sendImage)];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5([sendData bytes], [sendData length], digest);
    char md5cstring[CC_MD5_DIGEST_LENGTH*2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        sprintf(md5cstring+i*2, "%02x", digest[i]);
    }
    NSString *hash = [NSString stringWithCString:md5cstring encoding:NSASCIIStringEncoding];
    EDAMData * imageData = [[EDAMData alloc] initWithBodyHash:[hash dataUsingEncoding: NSASCIIStringEncoding]
                                                         size:[sendData length]
                                                         body:sendData];
    EDAMResourceAttributes * imageAttributes = [[EDAMResourceAttributes alloc] init];    
    EDAMResource * imageResource  = [[EDAMResource alloc]init];
    [imageResource setMime:@"image/png"];
    [imageResource setData:imageData];
    [imageResource setAttributes:imageAttributes];
    
    // create content xml from contentBody
    NSMutableString *xmlContents = [NSMutableString string];
    [xmlContents setString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"];
    [xmlContents appendString:@"<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml.dtd\">"];
    [xmlContents appendString:@"<en-note>"];
    [xmlContents appendString:contentBody];
    [xmlContents appendFormat:@"<br/><en-media type=\"image/png\" hash=\"%@\"/><br/>", hash];
    [xmlContents appendString:@"</en-note>"];

    // create note obj
    EDAMNoteAttributes *newNoteAttributes = [[EDAMNoteAttributes alloc]init];
    EDAMNote *newNote = [[EDAMNote alloc] init];
    [newNote setTitle:title];
    [newNote setContent:xmlContents];
    [newNote setTagNames:tagNames];
    [newNote setAttributes:newNoteAttributes];
    [newNote setCreated:(long long)[[NSDate date] timeIntervalSince1970] * 1000];
    [newNote setResources:[NSArray arrayWithObject:imageResource]];

    // create note
    EvernoteNoteStore *noteStore = [EvernoteNoteStore noteStore];
    [noteStore createNote:newNote
                  success:^(EDAMNote *note) {
                      NSLog(@"createNote succeed");
                  }
                  failure:^(NSError *error) {
                      NSLog(@"createNote error %@", error);
                  }];
}
34
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?