[英]How to read a file from the Documents directory asynchronously in ios
我想異步讀取存儲在Documents目錄中的本地文件。 我的代碼如下:
-(NSString *)getLogFilePath
{
NSString *logFileNameString = logFile;
return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:logFileNameString];
}
-(NSString *)readStringFromFile
{
NSString *fileAtPath = [self getLogFilePath];
return [[NSString alloc] initWithData:[NSDataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
請有人在這方面幫助我。 提前致謝。
使用Grand Central Dispatch和Block語法來做到這一點,
+(void) readStringFromFileWithCompletion:(void (^)(BOOL success,NSString *output))completionBlock{
dispatch_queue_t myQueue = dispatch_queue_create("FileReadingQueue",NULL);
dispatch_async(myQueue, ^{
// Perform long running process
NSString *fileAtPath = [self getLogFilePath];
NSString *output = [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
completionBlock(true,output);
});
}
用你的方法
[self readStringFromFileWithCompletion:^(BOOL success, NSString *output) {
// use 'output' here, to get the string read from file
}];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.