Как загрузить карту TMX из моего каталога документов?

Я загружаю карту TMX и Tileset со своего сервера и сохраняю их в каталоге документов приложений iOS:

- (void)downloadMap:(void (^)(NSURL *filePath))callback;
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    NSURL *URL = [NSURL URLWithString:@"http://localhost:9950/download"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
        return [documentsDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        DLog(@"Saved: %@", filePath);
        [self downloadTileMap:^(NSURL *filePath) {
            if (callback) {
                callback(filePath);
            }
        }];
    }];
    [downloadTask resume];
}

Это загружает оба ресурса. Затем я пытаюсь загрузить свою карту:

[self downloadMap:^(NSURL *filePath) {
    self.map = [CCTMXTiledMap tiledMapWithTMXFile:[filePath absoluteString]];
}];

И Cocos2D отказывается его загружать. Он не находит файлы, хотя в журналах указано:

Saved: file:///Users/ethan/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/2FDEA5E2-052D-4E7B-B7DD-3FA29B5BD4D0/Documents/test_map.tmx
Saved: file:///Users/ethan/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/2FDEA5E2-052D-4E7B-B7DD-3FA29B5BD4D0/Documents/tmw_desert_spacing.png
-[CCFileUtils fullPathForFilename:resolutionType:] : cocos2d: Warning: File not found: file:///Users/ethan/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/2FDEA5E2-052D-4E7B-B7DD-3FA29B5BD4D0/Documents/tmw_desert_spacing.png

И если я перечислю все файлы в каталоге Documents, я получу:

Files: (
    "test_map.tmx",
    "tmw_desert_spacing.png"
)

Я убедил себя, что файлы там. Карта TMX загружает набор тайлов как относительный путь:

<?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" orientation="orthogonal" width="16" height="40" tilewidth="32" tileheight="32">
 <tileset firstgid="1" name="tmw_desert_spacing" tilewidth="32" tileheight="32" spacing="1" margin="1">
  <image source="tmw_desert_spacing.png" width="265" height="199"/>
 </tileset>
 <layer name="Walkable" width="16" height="40">
  <data encoding="base64" compression="gzip">
   H4sIAAAAAAAAA+3DAQ0AAAzDoCqZf5kXckhYNVVV3zxRXBimAAoAAA==
  </data>
 </layer>
 <layer name="Collidable" width="16" height="40">
  <data encoding="base64" compression="gzip">
   H4sIAAAAAAAAA82TwQ5AMBBEV51wwgkHixP+//9cG9FNR2viJXMyk0llVgRDQT8TJXYwumIYA5o8z2D41oA2L78YviOg08vvhi83msnDwgEqH/I1oOYh3wHqE9+air789kXfFxSC7cHd8pVge6hv+VawPXQ5Hi28/8zqQYi5dWsXMbdu7SLm1q1d/AUl9cykHhYXallnFQAKAAA=
  </data>
 </layer>
</map>

Если бы это загружалось из Bundle, все было бы в порядке. Почему не работает из каталога Documents?


person Ethan Mick    schedule 09.03.2014    source источник
comment
Войдите в ccfileutils, пытаясь загрузить файл tmx. Это громоздко, но ccfileutils делает некоторые странные вещи, поэтому, если вы точно обнаружите, где что-то идет не так, это должно помочь вам понять проблему. Может быть даже вводящее в заблуждение предупреждение о том, что он не может найти изображение набора тайлов -hd.   -  person LearnCocos2D    schedule 10.03.2014


Ответы (1)


Я собираюсь зарегистрировать это как ошибку в cocos2d (или запрос функции). При попытке загрузить файл он попытается загрузить его только из пакета. Он просто не будет загружать его из каталога документов.

Итак, я исправил это!

В CCFileUtils.m:

- (NSString *)applicationDocumentsDirectory;
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
}

Это удобный метод для получения каталога приложения iOS.

Затем я меняю pathForResource:ofType:inDirectory: на:

-(NSString*) pathForResource:(NSString*)resource ofType:(NSString *)ext inDirectory:(NSString *)subpath
{
    // An absolute path could be used if the searchPath contains absolute paths
    if( [subpath isAbsolutePath] ) {
        NSString *fullpath = [subpath stringByAppendingPathComponent:resource];
        if( ext )
            fullpath = [fullpath stringByAppendingPathExtension:ext];

        if( [_fileManager fileExistsAtPath:fullpath] )
            return fullpath;
        return nil;
    }

    if (resource) {
        NSString *fullPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:resource];
        if( ext )
            fullPath = [fullPath stringByAppendingPathExtension:ext];

        if ([_fileManager fileExistsAtPath:fullPath]) {
            return fullPath;
        }
    }

    // Default to normal resource directory
    return [_bundle pathForResource:resource
                             ofType:ext
                        inDirectory:subpath];
}

По сути, прежде чем по умолчанию перейти в каталог Bundle, проверьте, существует ли ресурс в каталоге документов. Если да, то верни!

Теперь моя карта загружается без проблем.

person Ethan Mick    schedule 09.03.2014