[英]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.