기본 콘텐츠로 건너뛰기

XCode OS X Application : Drag & Drop 후 파일 처리


개인적으로 필요한 유틸이 있어서 appleScript 로 만들까하다가
XCode 4.4 로 OS X Application 을 만들어 본 적이 없어서
Drag & Drop, Pipe, File 처리 같은 걸 해봤다.

xib 에 드래그할 대상인 NSImageView 를 놓고
그 NSImageView 를 Customize 한 NSCImageView 를 만들어서 구현했다.
performDragOperation 이벤트에서 

NSPasteboard  *paste = [sender draggingPasteboard];
로 NSPasteboard 객체에 드래그 한 것들을 가지고
NSFilenamesPboardType 인것들을 타입으로 추출하여 NSData로 받았다.


NSArray *fileArray = [paste propertyListForType:@"NSFilenamesPboardType"];
파일 목록은 propertyListForType으로 string array 를 받을 수 있다.


shell 실행하고 결과 stdout 을 받는 것 처리하는데 위의 링크를 참조했다.

  NSTask *task = [[NSTask allocinit];
  [task setLaunchPath:@"<SHELL COMMAND>"];

NSTask 를 setLaunchPath 메서드를 사용하여 콜할 커맨드를 지정하고

  [task setArguments:[NSArray arrayWithObjects:<@args>, file, nil]];

N개의 argument 를 지정

  NSPipe *pipe=[NSPipe pipe];
  [task setStandardOutput:pipe];


실행 후 stdout 을 출력할 대상을 pipe 로 돌려놓고

  [task launch];

로 실행.

  NSFileHandle *fileHandle = [pipe fileHandleForReading];

파일 핸들은 아까 설정한 pipe 로부터 받았다.

  [fileHandle readDataToEndOfFile];

로 받으면 된다.
근데 기껏 만들고 나니 배포하는 법을 모르겠네;



#import "NSCImageView.h"

@implementation NSCImageView

- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
  if ((NSDragOperationGeneric & [sender draggingSourceOperationMask])==NSDragOperationGeneric) {
    return NSDragOperationGeneric;
  } else {
    return NSDragOperationNone;
  }
}

- (void)draggingExited:(id<NSDraggingInfo>)sender {
}

- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
  NSPasteboard *paste = [sender draggingPasteboard];
  NSString *desiredType = [paste availableTypeFromArray:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
  NSData *carriedData = [paste dataForType:desiredType];
  
  if (nil==carriedData) {
    return NO;
  } else {
    if ([desiredType isEqualToString:NSFilenamesPboardType]) {
      NSArray *fileArray = [paste propertyListForType:@"NSFilenamesPboardType"];
      NSTask *task = [[NSTask alloc] init];
      [task setLaunchPath:@"<SHELL COMMAND>"];
      for (NSString *file in fileArray) {
        [task setArguments:[NSArray arrayWithObjects:<@args>, file, nil]];
        NSPipe *pipe=[NSPipe pipe];
        [task setStandardOutput:pipe];
        NSFileHandle *fileHandle = [pipe fileHandleForReading];
        [task launch];
        NSData *data;
        data = [fileHandle readDataToEndOfFile];
        NSString *string;
        string=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"filename : %@", file);
        [fileHandle closeFile];
        
        [[NSFileManager defaultManager] createFileAtPath:file contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
      }
    } else {
      NSLog(@"Nothing happened");
    }
  }
  [self setNeedsDisplay:YES];
  return YES;
}
@end

댓글

이 블로그의 인기 게시물

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면

OS X 터미널에서 tmux 사용시 pane 크기 조절

http://superuser.com/a/660072  글 참조. OS X 에서 tmux 사용시 나눠놓은 pane 크기 조정할 때 원래는 ctrl+b, ctrl+↑←→↓ 로 사이즈를 조정하는데 기본 터미널 키 입력이 조금 문제가 있다. 키 매핑을 다시 하자 Preferences(cmd+,) > Profile >  변경하고자 하는 Theme 선택 > Keyboards 로 들어가서 \033[1;5A \033[1;5B \033[1;5C \033[1;5D 를 순서대로 ↑↓→←순으로 매핑이 되도록 하면 된다. +를 누르고 Key에 해당 화살표키와 Modifier에 ctrl 선택 한 후 <esc>, [, 1, ;, 5 까지 한키 한키 입력 후 A,B,C,D를 써준다. 잘못 입력했을 땐 당황하지 말고 Delete on character 버튼을 눌러 수정하도록 하자. 그리고 다시 tmux에서 ctrl+b, ctrl+↑←→↓로 사이즈를 조절해보자. 잘 된다.