2011-08-26 5 views
3

나는 phonegap 응용 프로그램을 가지고 있으며 매우 단순한 "Documents has exist"명령을 Documents 폴더에서 실행하려고합니다. 그리고 대부분 작동하고 있습니다. JS, 나는이 :객관적인 c에서 javascript로 변수를 반환합니다.

fileDownloadMgr.fileexists("logo.png"); 
...... 
PixFileDownload.prototype.fileexists = function(filename) { 
    PhoneGap.exec("PixFileDownload.fileExists", filename); 
}; 

그런 다음 목표 C에서, 내가 가진 :

-(BOOL) fileExists:(NSMutableArray*)paramArray withDict:(NSMutableDictionary*)options;{ 
    NSString * fileName = [paramArray objectAtIndex:0]; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *newFilePath = [documentsDirectory stringByAppendingString:[NSString stringWithFormat: @"/%@", fileName]]; 

    BOOL isMyFileThere = [[NSFileManager defaultManager] fileExistsAtPath:newFilePath]; 

    //i'm stuck here 
} 

나는 논리가 작업을 수행하고 BOOL이 설정되어 있는지 확인하기 위해 콘솔에이를 인쇄 할 NSLog를 사용할 수 있습니다 바르게. 하지만 자바 스크립트 세계에서 다시 변수가 필요합니다. 나는 stringByEvaluatingJavaScriptFromString을 알고 있지만 자바 스크립트 만 실행한다. 콜백 함수를 호출한다. 즉, 내가 여기에 필요하지, 난 (자바 스크립트)가 필요합니다 :

난 다시 자바 스크립트로 목표 C에서 해당 부울을 반환해야 할 일을
var bool = fileDownloadMgr.fileexists("logo.png"); 
if(bool) alert('The file is there!!!!!!'); 

?

답변

6

PhoneGap.exec에 대한 호출이 비동기 적이므로 호출 된 Objective-C 메서드가 성공할 때 호출되는 함수를 전달해야합니다. PhoneGap.exec

PixFileDownload.prototype.fileexists = function(filename, success) { 
    PhoneGap.exec(success, null, "PixFileDownload", "fileExists", filename); 
}; 

두 번째 인수가 오류 처리기를 사용하지 않은 여기에 있습니다 : 성공 핸들러에게 fileexists에 인수 (나중에 설명하는 이유를) 확인하십시오.

Obj-C 방법 내에서 PluginResult을 사용하여 -resultWithStatus:messageAsInt: 메서드를 통해 결과 함수를 성공 함수에 전달합니다.

-(BOOL) fileExists:(NSMutableArray*)paramArray withDict:(NSMutableDictionary*)options;{ 
    ... 
    //i'm stuck here 
    /* Create the result */ 
    PluginResult* pluginResult = [PluginResult resultWithStatus:PGCommandStatus_OK 
               messageAsInt:isMyFileThere]; 
    /* Create JS to call the success function with the result */ 
    NSString *successScript = [pluginResult toSuccessCallbackString:self.callbackID]; 
    /* Output the script */ 
    [self writeJavascript:successScript]; 

    /* The last two lines can be combined; they were separated to illustrate each 
    * step. 
    */ 
    //[self writeJavascript: [pluginResult toSuccessCallbackString:self.callbackID]]; 
} 

하여 obj-C에있어서, 에러 상황이 발생할 오차 함수를 호출하는 스크립트를 생성하는 PluginResulttoErrorCallbackString:를 사용할 수있는 경우

. PhoneGap.exec의 두 번째 인수로 오류 처리기를 전달해야합니다.

조정 & Continuations를

이제 fileexistssuccess 매개 변수를 추가하기위한 약속 설명. "조정 (coordination)"은 계산의 기능으로 코드가 의존하는 계산이 완료 될 때까지 실행되지 않습니다. 동기식 호출은 계산이 완료 될 때까지 함수가 반환되지 않기 때문에 무료로 조정을 제공합니다. 비동기 호출에서는 조정을 처리해야합니다. 종속 코드를 "continuation"("주어진 포인트에서 계산의 나머지 부분"을 의미 함) 함수에 묶고이 연속을 비동기 함수에 전달하여이 작업을 수행합니다. 이것은 (놀라지 않게) continuation passing style (CPS)라고합니다. 동기 호출과 함께 CPS를 사용할 수 있다는 점에 유의하십시오.

PhoneGap.exec은 비동기식이므로 성공시 호출하고 실패 할 때 계속 호출 할 수 있습니다. fileexists은 비동기 함수에 따라 다르므로 비동기이므로 연속성을 전달해야합니다. fileDownloadMgr.fileexists("logo.png"); 뒤의 코드는 fileexists에 전달 된 함수로 래핑되어야합니다. 예를 들어, 처음에 다음 항목을 가지고 있었다면 :

if (fileDownloadMgr.fileexists("logo.png")) { 
    ... 
} else { 
    ... 
} 

연속 만들기는 여러 연속이있을 때 약간 털이 나올 수 있지만 연속 작성은 간단합니다.변수와 비동기 함수 호출을 대체하는 기능으로 if 문을 다시 작성 :

function (x) { 
    if (x) { 
     ... 
    } else { 
     ... 
    } 
} 

그런 다음 fileexists이 계속 전달 :

fileDownloadMgr.fileexists("logo.png", function (exists) { 
    if (exists) { 
     ... 
    } else { 
     ... 
    } 
}); 

를 더 읽기

나는 할 수 없었다 PluginResult-resultWithStatus:messageAsInt:을 찾으십시오. 그러나 "How to Create a PhoneGap Plugin for iOS"의 Obj-C 메서드에서 JS로 다시 값을 반환하는 방법을 보여주는 예제가 있습니다. API 문서의 PhoneGap.exec에 대한 설명서는 현재 다소 부족합니다. 둘 다 Wiki 페이지이므로, 아마도 나 또는 다른 누군가가 Wiki 페이지를 향상시킬 시간을 찾을 것입니다. PluginResult에 대한 headerimplementation 파일도 있습니다.

+0

outis 나는 연속의 구현까지 여러분을 따라갑니다. 좀 더 명확한 예제를 제공해 주시겠습니까? 감사 – user7865437

관련 문제