-1

我正在尝试在我的 iPad 上编译应用程序。我正在使用 AFNetworking 来获取我的 FTP 上的文件列表。应用程序在模拟器上运行,但是当我在 iPad 上启动它时,我得到(空)文件内容和列表。这是代码:

- (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);
}

所以 variable content = (null) 只在 iPad 上,在 Simulator 上一切都很好。请帮忙,我已经失去了任何希望)

4

2 回答 2

1

默认情况下,AFHTTP*Operations 都是异步的。

这是正确的,因为同步(阻塞)调用阻塞了主线程

您正在开始操作并在之后直接获取文件内容。这不能可靠地工作,因为开始调用是 ASYNC 并且只启动操作但不等待它

要么等待它......这很糟糕,因为它阻塞了线程:

[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];
}
于 2013-01-28T09:09:32.567 回答
0

好的,问题解决了。我无法写入捆绑目录,所以我需要使用下一个代码:

NSArray *paths = NSSearchPathForDirectoiesDomain(NSDocumentDirectory,NSCachesDirectory,YES);
NSString *path = [[paths objectAtIndex:0] stingByAppendingPathComponent:@"list"];
于 2013-01-29T00:11:49.147 回答