我正在尝试在iPad上编译应用程序。我正在使用AFNetworking来获取FTP上的文件列表。应用程序在模拟器上工作,但是当我在iPad上启动时,我得到(null)带有列表的文件内容。这是代码:
- (void) getListOfFiles {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"ftp://anonymous@ftphost/"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *path = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"list"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:YES];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, NSHTTPURLResponse *response) {
NSLog(@"Success %@",operation.response);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", [error localizedDescription]);
}];
[operation start];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog (@"%@",content);
}
仅在iPad上变量内容=(null),在模拟器上一切都很好。请帮助,我已经失去了任何希望)
答案 0 :(得分:1)
AFHTTP *默认情况下,操作都是异步的。
这是正确的,因为同步(阻塞)调用会阻塞主线程
您正在开始操作并随后直接获取文件内容。这不能可靠地工作,因为启动调用是ASYNC并且只启动操作但不等待它
要等待才能... 这是BAD ,因为它阻止了线程:
[operation start];
[operation waitUntilDone];
或更好将getFiles修改为异步工作:
- (void) getListOfFiles {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"URL"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *path = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"list"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:YES];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, NSHTTPURLResponse *response) {
NSLog(@"Success %@",operation.response);
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog (@"%@",content);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", [error localizedDescription]);
}];
[operation start];
}
答案 1 :(得分:0)
好的,问题解决了。我无法写入bundle目录,所以我需要使用下一个代码:
NSArray *paths = NSSearchPathForDirectoiesDomain(NSDocumentDirectory,NSCachesDirectory,YES);
NSString *path = [[paths objectAtIndex:0] stingByAppendingPathComponent:@"list"];