diff --git a/platform/darwin/src/MGLOfflineStorage.h b/platform/darwin/src/MGLOfflineStorage.h index d093bb938..3621e1624 100644 --- a/platform/darwin/src/MGLOfflineStorage.h +++ b/platform/darwin/src/MGLOfflineStorage.h @@ -142,6 +142,15 @@ typedef void (^MGLOfflinePackRemovalCompletionHandler)(NSError * _Nullable error */ typedef void (^MGLBatchedOfflinePackAdditionCompletionHandler)(NSURL *fileURL, NSArray * _Nullable packs, NSError * _Nullable error); +/** +A block to be called once the data has been preloaded. + + @param url The URL of the data that was pre-loaded. + @param error Contains a pointer to an error object (if any) indicating why the + data could not be pre-loaded. +*/ +typedef void (^MGLOfflinePreloadDataCompletionHandler)(NSURL * url, NSError * _Nullable error); + /** The type of resource that is requested. */ @@ -434,7 +443,9 @@ MGL_EXPORT This method is asynchronous; the data may not be immediately available for in-progress requests, though subsequent requests should have access to the cached data. - + + To find out when the resource is ready to retrieve from the cache, use the -preloadData:forURL:modificationDate:expirationDate:eTag:mustRevalidate:completionHandler: method. + @param data Response data to store for this resource. The data is expected to be uncompressed; internally, the cache will compress data as necessary. @param url The URL at which the data can normally be found. @@ -448,6 +459,30 @@ MGL_EXPORT - (void)putResourceWithUrl:(NSURL *)url data:(NSData *)data modified:(nullable NSDate *)modified expires:(nullable NSDate *)expires etag:(nullable NSString *)etag mustRevalidate:(BOOL)mustRevalidate __attribute__((deprecated("", "-preloadData:forURL:modificationDate:expirationDate:eTag:mustRevalidate:"))); +/** +Inserts the provided resource into the ambient cache, calling a completion handler when finished. + +This method is asynchronous. The data is available for in-progress requests as +soon as the completion handler is called. + +This method is asynchronous; the data may not be immediately available for +in-progress requests, though subsequent requests should have access to the +cached data. + +@param data Response data to store for this resource. The data is expected to + be uncompressed; internally, the cache will compress data as necessary. +@param url The URL at which the data can normally be found. +@param modified The date the resource was last modified. +@param expires The date after which the resource is no longer valid. +@param eTag An HTTP entity tag. +@param mustRevalidate A Boolean value indicating whether the data is still + usable past the expiration date. +@param completion The completion handler to call once the data has been preloaded. +This handler is executed asynchronously on the main queue. +*/ +- (void)preloadData:(NSData *)data forURL:(NSURL *)url modificationDate:(nullable NSDate *)modified expirationDate:(nullable NSDate *)expires eTag:(nullable NSString *)eTag mustRevalidate:(BOOL)mustRevalidate + completionHandler:(nullable MGLOfflinePreloadDataCompletionHandler)completion; + @end /** diff --git a/platform/darwin/src/MGLOfflineStorage.mm b/platform/darwin/src/MGLOfflineStorage.mm index 0ccde6373..daa7dd58a 100644 --- a/platform/darwin/src/MGLOfflineStorage.mm +++ b/platform/darwin/src/MGLOfflineStorage.mm @@ -80,7 +80,9 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio if (self.isPaused) { return; } - _mbglFileSource->pause(); + + _mbglOnlineFileSource->pause(); + _mbglDatabaseFileSource->pause(); self.paused = YES; } @@ -88,7 +90,9 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio if (!self.isPaused) { return; } - _mbglFileSource->resume(); + + _mbglOnlineFileSource->pause(); + _mbglDatabaseFileSource->pause(); self.paused = NO; } #endif @@ -281,9 +285,9 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio } else if ([keyPath isEqualToString:@"apiBaseURL"] && object == [MGLAccountManager sharedManager]) { NSURL *apiBaseURL = change[NSKeyValueChangeNewKey]; if ([apiBaseURL isKindOfClass:[NSNull class]]) { - _mbglFileSource->setProperty(mbgl::API_BASE_URL_KEY, mbgl::util::API_BASE_URL); + _mbglOnlineFileSource->setProperty(mbgl::API_BASE_URL_KEY, mbgl::util::API_BASE_URL); } else { - _mbglFileSource->setProperty(mbgl::API_BASE_URL_KEY, apiBaseURL.absoluteString.UTF8String); + _mbglOnlineFileSource->setProperty(mbgl::API_BASE_URL_KEY, apiBaseURL.absoluteString.UTF8String); } } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; @@ -633,6 +637,11 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio } - (void)preloadData:(NSData *)data forURL:(NSURL *)url modificationDate:(nullable NSDate *)modified expirationDate:(nullable NSDate *)expires eTag:(nullable NSString *)eTag mustRevalidate:(BOOL)mustRevalidate { + [self preloadData:data forURL:url modificationDate:modified expirationDate:expires eTag:eTag mustRevalidate:mustRevalidate completionHandler:nil]; +} + +- (void)preloadData:(NSData *)data forURL:(NSURL *)url modificationDate:(nullable NSDate *)modified expirationDate:(nullable NSDate *)expires eTag:(nullable NSString *)eTag mustRevalidate:(BOOL)mustRevalidate + completionHandler:(nullable MGLOfflinePreloadDataCompletionHandler)completion { mbgl::Resource resource(mbgl::Resource::Kind::Unknown, url.absoluteString.UTF8String); mbgl::Response response; response.data = std::make_shared(static_cast(data.bytes), data.length); @@ -649,8 +658,16 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio if (expires) { response.expires = mbgl::Timestamp() + std::chrono::duration_cast(MGLDurationFromTimeInterval(expires.timeIntervalSince1970)); } - - _mbglDatabaseFileSource->put(resource, response); + + std::function callback; + + if (completion) { + callback = [completion, url] { + dispatch_async(dispatch_get_main_queue(), [completion, url] { completion(url, nil); }); + }; + } + + _mbglDatabaseFileSource->forward(resource, response, callback); } - (void)putResourceWithUrl:(NSURL *)url data:(NSData *)data modified:(nullable NSDate *)modified expires:(nullable NSDate *)expires etag:(nullable NSString *)etag mustRevalidate:(BOOL)mustRevalidate { diff --git a/platform/darwin/test/MGLOfflineStorageTests.mm b/platform/darwin/test/MGLOfflineStorageTests.mm index 8f6114658..824ce9f6e 100644 --- a/platform/darwin/test/MGLOfflineStorageTests.mm +++ b/platform/darwin/test/MGLOfflineStorageTests.mm @@ -54,6 +54,16 @@ }); } +- (NSURL *)offlineStorage:(MGLOfflineStorage *)storage + URLForResourceOfKind:(MGLResourceKind)kind + withURL:(NSURL *)url { + if ([url.scheme isEqual: @"test"] && [url.host isEqual: @"api"]) { + return [NSURL URLWithString:@"https://api.mapbox.com"]; + } else { + return url; + } +} + - (void)testSharedObject { XCTAssertEqual([MGLOfflineStorage sharedOfflineStorage], [MGLOfflineStorage sharedOfflineStorage], @"There should only be one shared offline storage object."); } @@ -133,7 +143,7 @@ - (void)testAddPackForGeometry { NSUInteger countOfPacks = [MGLOfflineStorage sharedOfflineStorage].packs.count; - + NSURL *styleURL = [MGLStyle lightStyleURLWithVersion:8]; double zoomLevel = 20; NSString *geojson = @"{ \"type\": \"Polygon\", \"coordinates\": [ [ [ 5.1299285888671875, 52.10365839097971 ], [ 5.103063583374023, 52.110037078604236 ], [ 5.080232620239258, 52.09548601177304 ], [ 5.106925964355469, 52.07987524347506 ], [ 5.1299285888671875, 52.10365839097971 ] ] ]}"; @@ -142,12 +152,12 @@ XCTAssertNil(error); MGLShapeOfflineRegion *region = [[MGLShapeOfflineRegion alloc] initWithStyleURL:styleURL shape:shape fromZoomLevel:zoomLevel toZoomLevel:zoomLevel]; region.includesIdeographicGlyphs = NO; - + NSString *nameKey = @"Name"; NSString *name = @"Utrecht centrum"; - + NSData *context = [NSKeyedArchiver archivedDataWithRootObject:@{nameKey: name}]; - + __block MGLOfflinePack *pack; [self keyValueObservingExpectationForObject:[MGLOfflineStorage sharedOfflineStorage] keyPath:@"packs" handler:^BOOL(id _Nonnull observedObject, NSDictionary * _Nonnull change) { const auto changeKind = static_cast([change[NSKeyValueChangeKindKey] unsignedLongValue]); @@ -162,20 +172,20 @@ [additionCompletionHandlerExpectation fulfill]; }]; [self waitForExpectationsWithTimeout:5 handler:nil]; - + XCTAssertEqual([MGLOfflineStorage sharedOfflineStorage].packs.count, countOfPacks + 1, @"Added pack should have been added to the canonical collection of packs owned by the shared offline storage object. This assertion can fail if this test is run before -testAAALoadPacks."); - + XCTAssertEqual(pack, [MGLOfflineStorage sharedOfflineStorage].packs.lastObject, @"Pack should be appended to end of packs array."); - + XCTAssertEqualObjects(pack.region, region, @"Added pack’s region has changed."); - + NSDictionary *userInfo = [NSKeyedUnarchiver unarchiveObjectWithData:pack.context]; XCTAssert([userInfo isKindOfClass:[NSDictionary class]], @"Context of offline pack isn’t a dictionary."); XCTAssert([userInfo[nameKey] isKindOfClass:[NSString class]], @"Name of offline pack isn’t a string."); XCTAssertEqualObjects(userInfo[nameKey], name, @"Name of offline pack has changed."); - + XCTAssertEqual(pack.state, MGLOfflinePackStateInactive, @"New pack should initially have inactive state."); - + [self keyValueObservingExpectationForObject:pack keyPath:@"state" handler:^BOOL(id _Nonnull observedObject, NSDictionary * _Nonnull change) { const auto changeKind = static_cast([change[NSKeyValueChangeKindKey] unsignedLongValue]); const auto state = static_cast([change[NSKeyValueChangeNewKey] longValue]); @@ -184,18 +194,18 @@ [self expectationForNotification:MGLOfflinePackProgressChangedNotification object:pack handler:^BOOL(NSNotification * _Nonnull notification) { MGLOfflinePack *notificationPack = notification.object; XCTAssert([notificationPack isKindOfClass:[MGLOfflinePack class]], @"Object of notification should be an MGLOfflinePack."); - + NSDictionary *userInfo = notification.userInfo; XCTAssertNotNil(userInfo, @"Progress change notification should have a userInfo dictionary."); - + NSNumber *stateNumber = userInfo[MGLOfflinePackUserInfoKeyState]; XCTAssert([stateNumber isKindOfClass:[NSNumber class]], @"Progress change notification’s state should be an NSNumber."); XCTAssertEqual(stateNumber.integerValue, pack.state, @"State in a progress change notification should match the pack’s state."); - + NSValue *progressValue = userInfo[MGLOfflinePackUserInfoKeyProgress]; XCTAssert([progressValue isKindOfClass:[NSValue class]], @"Progress change notification’s progress should be an NSValue."); XCTAssertEqualObjects(progressValue, [NSValue valueWithMGLOfflinePackProgress:pack.progress], @"Progress change notification’s progress should match pack’s progress."); - + return notificationPack == pack && pack.state == MGLOfflinePackStateInactive; }]; [pack requestProgress]; @@ -209,13 +219,13 @@ { .latitude = 48.8660, .longitude = 2.3306 }, { .latitude = 48.8603, .longitude = 2.3213 }, }; - + NSURL *styleURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"one-liner" withExtension:@"json"]; MGLTilePyramidOfflineRegion *region = [[MGLTilePyramidOfflineRegion alloc] initWithStyleURL:styleURL bounds:bounds fromZoomLevel:10 toZoomLevel:11]; - + NSString *nameKey = @"Name"; NSString *name = @"Paris square"; - + NSData *context = [NSKeyedArchiver archivedDataWithRootObject:@{nameKey: name}]; [[MGLOfflineStorage sharedOfflineStorage] addPackForRegion:region withContext:context completionHandler:^(MGLOfflinePack * _Nullable pack, NSError * _Nullable error) { XCTAssertNotNil(pack); @@ -228,41 +238,27 @@ [self waitForExpectationsWithTimeout:10 handler:nil]; } -- (void)testSetMaximumAmbientCache { - XCTestExpectation *expectation = [self expectationWithDescription:@"Expect maximum cache size to be raised without an error."]; - [[MGLOfflineStorage sharedOfflineStorage] setMaximumAmbientCacheSize:0 withCompletionHandler:^(NSError * _Nullable error) { - XCTAssertNil(error); - [expectation fulfill]; - }]; - - [self waitForExpectationsWithTimeout:10 handler:nil]; -} +- (void)testRemovePack { + NSUInteger countOfPacks = [MGLOfflineStorage sharedOfflineStorage].packs.count; -- (void)testInvalidateAmbientCache { - XCTestExpectation *expectation = [self expectationWithDescription:@"Expect cache to be invalidated without an error."]; - [[MGLOfflineStorage sharedOfflineStorage] invalidateAmbientCacheWithCompletionHandler:^(NSError * _Nullable error) { - XCTAssertNil(error); - [expectation fulfill]; - }]; - [self waitForExpectationsWithTimeout:10 handler:nil]; -} + MGLOfflinePack *pack = [MGLOfflineStorage sharedOfflineStorage].packs.lastObject; + XCTAssertNotNil(pack, @"Added pack should still exist."); -- (void)testClearCache { - XCTestExpectation *expectation = [self expectationWithDescription:@"Expect cache to be cleared without an error."]; - [[MGLOfflineStorage sharedOfflineStorage] clearAmbientCacheWithCompletionHandler:^(NSError * _Nullable error) { - XCTAssertNil(error); - [expectation fulfill]; + [self keyValueObservingExpectationForObject:[MGLOfflineStorage sharedOfflineStorage] keyPath:@"packs" handler:^BOOL(id _Nonnull observedObject, NSDictionary * _Nonnull change) { + const auto changeKind = static_cast([change[NSKeyValueChangeKindKey] unsignedLongValue]); + NSIndexSet *indices = change[NSKeyValueChangeIndexesKey]; + return changeKind == NSKeyValueChangeRemoval && indices.count == 1; }]; - [self waitForExpectationsWithTimeout:10 handler:nil]; -} + XCTestExpectation *completionHandlerExpectation = [self expectationWithDescription:@"remove pack completion handler"]; + [[MGLOfflineStorage sharedOfflineStorage] removePack:pack withCompletionHandler:^(NSError * _Nullable error) { + XCTAssertEqual(pack.state, MGLOfflinePackStateInvalid, @"Removed pack should be invalid in the completion handler."); + [completionHandlerExpectation fulfill]; + }]; + [self waitForExpectationsWithTimeout:5 handler:nil]; -- (void)testResetDatabase { - XCTestExpectation *expectation = [self expectationWithDescription:@"Expect database to be reset without an error."]; - [[MGLOfflineStorage sharedOfflineStorage] resetDatabaseWithCompletionHandler:^(NSError * _Nullable error) { - XCTAssertNil(error); - [expectation fulfill]; - }]; - [self waitForExpectationsWithTimeout:10 handler:nil]; + XCTAssertEqual(pack.state, MGLOfflinePackStateInvalid, @"Removed pack should have been invalidated synchronously."); + + XCTAssertEqual([MGLOfflineStorage sharedOfflineStorage].packs.count, countOfPacks - 1, @"Removed pack should have been removed from the canonical collection of packs owned by the shared offline storage object. This assertion can fail if this test is run before -testAAALoadPacks or -testAddPack."); } - (void)testBackupExclusion { @@ -289,50 +285,27 @@ XCTAssertNil(error, @"No errors should be returned when checking backup exclusion flag."); } -- (void)testRemovePack { - NSUInteger countOfPacks = [MGLOfflineStorage sharedOfflineStorage].packs.count; - - MGLOfflinePack *pack = [MGLOfflineStorage sharedOfflineStorage].packs.lastObject; - XCTAssertNotNil(pack, @"Added pack should still exist."); - - [self keyValueObservingExpectationForObject:[MGLOfflineStorage sharedOfflineStorage] keyPath:@"packs" handler:^BOOL(id _Nonnull observedObject, NSDictionary * _Nonnull change) { - const auto changeKind = static_cast([change[NSKeyValueChangeKindKey] unsignedLongValue]); - NSIndexSet *indices = change[NSKeyValueChangeIndexesKey]; - return changeKind == NSKeyValueChangeRemoval && indices.count == 1; - }]; - XCTestExpectation *completionHandlerExpectation = [self expectationWithDescription:@"remove pack completion handler"]; - [[MGLOfflineStorage sharedOfflineStorage] removePack:pack withCompletionHandler:^(NSError * _Nullable error) { - XCTAssertEqual(pack.state, MGLOfflinePackStateInvalid, @"Removed pack should be invalid in the completion handler."); - [completionHandlerExpectation fulfill]; - }]; - [self waitForExpectationsWithTimeout:5 handler:nil]; - - XCTAssertEqual(pack.state, MGLOfflinePackStateInvalid, @"Removed pack should have been invalidated synchronously."); - - XCTAssertEqual([MGLOfflineStorage sharedOfflineStorage].packs.count, countOfPacks - 1, @"Removed pack should have been removed from the canonical collection of packs owned by the shared offline storage object. This assertion can fail if this test is run before -testAAALoadPacks or -testAddPack."); -} - - (void)addPacks:(NSInteger)count { - + XCTestExpectation *expectation = [self expectationWithDescription:@"added packs"]; NSURL *styleURL = [MGLStyle lightStyleURLWithVersion:8]; - + MGLCoordinateBounds bounds[] = { {{51.5, -0.2}, {51.6, -0.1}}, // London {{60.1, 24.8}, {60.3, 25.1}}, // Helsinki {{38.9, -77.1}, {38.9, -77.0}}, // DC {{37.7, -122.5}, {37.9, -122.4}} // SF }; - + int arraySize = sizeof(bounds)/sizeof(bounds[0]); - + count = MIN(count, arraySize); - + dispatch_group_t group = dispatch_group_create(); - + for (int i = 0; i < count; i++) { - + dispatch_group_enter(group); MGLTilePyramidOfflineRegion *region = [[MGLTilePyramidOfflineRegion alloc] initWithStyleURL:styleURL bounds:bounds[i] fromZoomLevel:20 toZoomLevel:20]; NSData *context = [NSKeyedArchiver archivedDataWithRootObject:@{ @@ -344,22 +317,22 @@ completionHandler:^(MGLOfflinePack * _Nullable pack, NSError * _Nullable error) { XCTAssertNotNil(pack); XCTAssertNil(error); - + dispatch_group_leave(group); }]; } - + dispatch_group_notify(group, dispatch_get_main_queue(), ^{ [expectation fulfill]; }); - + [self waitForExpectations:@[expectation] timeout:1.0]; } - (void)testRemovePackTwiceInSuccession { [self addPacks:1]; - + NSUInteger countOfPacks = [MGLOfflineStorage sharedOfflineStorage].packs.count; MGLOfflinePack *pack = [MGLOfflineStorage sharedOfflineStorage].packs.lastObject; @@ -370,7 +343,7 @@ NSIndexSet *indices = change[NSKeyValueChangeIndexesKey]; return changeKind == NSKeyValueChangeRemoval && indices.count == 1; }]; - + XCTestExpectation *completionHandlerExpectation = [self expectationWithDescription:@"remove pack completion handler"]; [[MGLOfflineStorage sharedOfflineStorage] removePack:pack withCompletionHandler:nil]; @@ -379,12 +352,12 @@ MGLTestAssertionHandler *newHandler = [[MGLTestAssertionHandler alloc] initWithTestCase:self]; [[[NSThread currentThread] threadDictionary] setValue:newHandler forKey:NSAssertionHandlerKey]; - + [[MGLOfflineStorage sharedOfflineStorage] removePack:pack withCompletionHandler:^(NSError * _Nullable error) { XCTAssertEqual(pack.state, MGLOfflinePackStateInvalid, @"Removed pack should be invalid in the completion handler."); [completionHandlerExpectation fulfill]; }]; - + [self waitForExpectationsWithTimeout:5 handler:nil]; [[[NSThread currentThread] threadDictionary] setValue:oldHandler forKey:NSAssertionHandlerKey]; @@ -392,7 +365,7 @@ XCTAssertEqual(pack.state, MGLOfflinePackStateInvalid, @"Removed pack should have been invalidated synchronously."); XCTAssertEqual([MGLOfflineStorage sharedOfflineStorage].packs.count, countOfPacks - 1, @"Removed pack should have been removed from the canonical collection of packs owned by the shared offline storage object. This assertion can fail if this test is run before -testAAALoadPacks or -testAddPack."); - + NSLog(@"Test `%@` complete", NSStringFromSelector(_cmd)); } @@ -405,22 +378,22 @@ // in offline.cpp // // Reloading packs, while trying to remove them is currently problematic. - + [self addPacks:4]; - + NSInteger countOfPacks = [MGLOfflineStorage sharedOfflineStorage].packs.count; XCTAssert(countOfPacks > 0); // Now delete packs one by one XCTestExpectation *expectation = [self expectationWithDescription:@"All packs removed"]; expectation.expectedFulfillmentCount = countOfPacks; - + MGLOfflineStorage *storage = [MGLOfflineStorage sharedOfflineStorage]; NSArray *packs = [storage.packs copy]; // Simulate what happens the first time sharedOfflineStorage is accessed [storage reloadPacks]; - + NSArray *validPacks = [packs filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject, NSDictionary * _Nullable bindings) { MGLOfflinePack *pack = (MGLOfflinePack*)evaluatedObject; return pack.state != MGLOfflinePackStateInvalid; @@ -436,13 +409,13 @@ [expectation fulfill]; }]; } - + [[[NSThread currentThread] threadDictionary] setValue:oldHandler forKey:NSAssertionHandlerKey]; - + [self waitForExpectations:@[expectation] timeout:10.0]; - + // TODO: What should we expect here? All packs removed? - + NSLog(@"Test `%@` complete", NSStringFromSelector(_cmd)); } @@ -450,56 +423,56 @@ - (void)test15536RemovePacksOnBackgroundQueueWhileReloading { [self addPacks:4]; - + NSInteger countOfPacks = [MGLOfflineStorage sharedOfflineStorage].packs.count; XCTAssert(countOfPacks > 0); // Now delete packs one by one dispatch_queue_t queue = dispatch_queue_create("com.mapbox.testRemovePacks", DISPATCH_QUEUE_SERIAL); - + XCTestExpectation *expectation = [self expectationWithDescription:@"all packs removed"]; expectation.expectedFulfillmentCount = countOfPacks; - + MGLOfflineStorage *storage = [MGLOfflineStorage sharedOfflineStorage]; - + // Simulate what happens the first time sharedOfflineStorage is accessed [storage reloadPacks]; // NSArray *packs = [storage.packs copy]; - + dispatch_async(queue, ^{ NSArray *packs = storage.packs; NSAssertionHandler *oldHandler = [NSAssertionHandler currentHandler]; MGLTestAssertionHandler *newHandler = [[MGLTestAssertionHandler alloc] initWithTestCase:self]; [[[NSThread currentThread] threadDictionary] setValue:newHandler forKey:NSAssertionHandlerKey]; - + NSArray *validPacks = [packs filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject, NSDictionary * _Nullable bindings) { MGLOfflinePack *pack = (MGLOfflinePack*)evaluatedObject; return pack.state != MGLOfflinePackStateInvalid; }]]; - + for (MGLOfflinePack *pack in validPacks) { // NOTE: pack can be invalid, as we have two threads potentially // modifying the same MGLOfflinePack. - + dispatch_group_t group = dispatch_group_create(); dispatch_group_enter(group); [storage removePack:pack withCompletionHandler:^(NSError * _Nullable error) { dispatch_group_leave(group); }]; dispatch_group_wait(group, DISPATCH_TIME_FOREVER); - + [expectation fulfill]; } - + [[[NSThread currentThread] threadDictionary] setValue:oldHandler forKey:NSAssertionHandlerKey]; }); - + [self waitForExpectations:@[expectation] timeout:60.0]; - + // TODO: What should we expect here? All packs removed? - + NSLog(@"Test `%@` complete", NSStringFromSelector(_cmd)); } @@ -507,21 +480,11 @@ XCTAssertGreaterThan([MGLOfflineStorage sharedOfflineStorage].countOfBytesCompleted, 0UL); } -- (NSURL *)offlineStorage:(MGLOfflineStorage *)storage - URLForResourceOfKind:(MGLResourceKind)kind - withURL:(NSURL *)url { - if ([url.scheme isEqual: @"test"] && [url.host isEqual: @"api"]) { - return [NSURL URLWithString:@"https://api.mapbox.com"]; - } else { - return url; - } -} - - (void)testResourceTransform { MGLOfflineStorage *os = [MGLOfflineStorage sharedOfflineStorage]; [os setDelegate:self]; - auto fs = os.mbglFileSource; + auto fs = os.mbglOnlineFileSource; // Delegate returns "https://api.mapbox.com" as a replacement URL. const mbgl::Resource resource { mbgl::Resource::Unknown, "test://api" }; @@ -555,15 +518,15 @@ long long databaseFileSize = 73728; // Merging databases creates an empty file if the file does not exist at the given path. XCTAssertEqual(fileSize, databaseFileSize, @"The database file size must be:%lld actual size:%lld", databaseFileSize, fileSize); - + NSUInteger countOfPacks = [MGLOfflineStorage sharedOfflineStorage].packs.count; - + [self keyValueObservingExpectationForObject:[MGLOfflineStorage sharedOfflineStorage] keyPath:@"packs" handler:^BOOL(id _Nonnull observedObject, NSDictionary * _Nonnull change) { const auto changeKind = static_cast([change[NSKeyValueChangeKindKey] unsignedLongValue]); NSIndexSet *indices = change[NSKeyValueChangeIndexesKey]; return changeKind == NSKeyValueChangeInsertion && indices.count == 1; }]; - + XCTestExpectation *fileAdditionCompletionHandlerExpectation = [self expectationWithDescription:@"add database content completion handler"]; MGLOfflineStorage *os = [MGLOfflineStorage sharedOfflineStorage]; [os addContentsOfURL:resourceURL withCompletionHandler:^(NSURL *fileURL, NSArray * _Nullable packs, NSError * _Nullable error) { @@ -605,7 +568,7 @@ // URL to a non-file [XCTContext runActivityNamed:@"URL to a non-file" block:^(id activity) { NSURL *resourceURL = [NSURL URLWithString:@"https://www.mapbox.com"]; - + MGLOfflineStorage *os = [MGLOfflineStorage sharedOfflineStorage]; XCTAssertThrowsSpecificNamed([os addContentsOfURL:resourceURL withCompletionHandler:nil], NSException, NSInvalidArgumentException, "MGLOfflineStorage should rise an exception if an invalid URL file is passed."); }]; @@ -613,59 +576,103 @@ - (void)testPutResourceForURL { NSURL *styleURL = [NSURL URLWithString:@"https://api.mapbox.com/some/thing"]; - + MGLOfflineStorage *os = [MGLOfflineStorage sharedOfflineStorage]; std::string testData("test data"); NSData *data = [NSData dataWithBytes:testData.c_str() length:testData.length()]; - [os preloadData:data forURL:styleURL modificationDate:nil expirationDate:nil eTag:nil mustRevalidate:NO]; - - auto fs = os.mbglFileSource; - const mbgl::Resource resource { mbgl::Resource::Unknown, "https://api.mapbox.com/some/thing" }; - std::unique_ptr req; - req = fs->request(resource, [&](mbgl::Response res) { - req.reset(); - XCTAssertFalse(res.error.get(), @"Request should not return an error"); - XCTAssertTrue(res.data.get(), @"Request should return data"); - XCTAssertFalse(res.modified, @"Request should not have a modification timestamp"); - XCTAssertFalse(res.expires, @"Request should not have an expiration timestamp"); - XCTAssertFalse(res.etag, @"Request should not have an entity tag"); - XCTAssertFalse(res.mustRevalidate, @"Request should not require revalidation"); - XCTAssertEqual("test data", *res.data, @"Request did not return expected data"); - CFRunLoopStop(CFRunLoopGetCurrent()); - }); - + __block std::unique_ptr req; + [os preloadData:data forURL:styleURL modificationDate:nil expirationDate:nil eTag:nil mustRevalidate:NO completionHandler:^(NSURL * url, NSError * _Nullable error) { + XCTAssertFalse(error, @"preloadData should not return an error"); + XCTAssertEqual(styleURL, url, @"Preloaded resource url is invalid"); + + auto fs = os.mbglDatabaseFileSource; + const mbgl::Resource resource { mbgl::Resource::Unknown, "https://api.mapbox.com/some/thing" }; + req = fs->request(resource, [&](mbgl::Response res) { + XCTAssertFalse(res.error.get(), @"Request should not return an error"); + XCTAssertTrue(res.data.get(), @"Request should return data"); + XCTAssertFalse(res.modified, @"Request should not have a modification timestamp"); + XCTAssertFalse(res.expires, @"Request should not have an expiration timestamp"); + XCTAssertFalse(res.etag, @"Request should not have an entity tag"); + XCTAssertFalse(res.mustRevalidate, @"Request should not require revalidation"); + XCTAssertEqual("test data", *res.data, @"Request did not return expected data"); + CFRunLoopStop(CFRunLoopGetCurrent()); + }); + }]; + CFRunLoopRun(); } - (void)testPutResourceForURLWithTimestamps { - NSURL *styleURL = [NSURL URLWithString:@"https://api.mapbox.com/some/thing"]; - + NSURL *styleURL = [NSURL URLWithString:@"https://api.mapbox.com/some/thing1"]; + MGLOfflineStorage *os = [MGLOfflineStorage sharedOfflineStorage]; std::string testData("test data"); - NSDate *now = [NSDate date]; - NSDate *future = [now dateByAddingTimeInterval:600]; NSData *data = [NSData dataWithBytes:testData.c_str() length:testData.length()]; - [os preloadData:data forURL:styleURL modificationDate:now expirationDate:future eTag:@"some etag" mustRevalidate:YES]; - - auto fs = os.mbglFileSource; - const mbgl::Resource resource { mbgl::Resource::Unknown, "https://api.mapbox.com/some/thing" }; - std::unique_ptr req; - req = fs->request(resource, [&](mbgl::Response res) { - req.reset(); - XCTAssertFalse(res.error.get(), @"Request should not return an error"); - XCTAssertTrue(res.data.get(), @"Request should return data"); - XCTAssertTrue(res.modified, @"Request should have a modification timestamp"); - XCTAssertEqual(MGLTimeIntervalFromDuration(res.modified->time_since_epoch()), floor(now.timeIntervalSince1970), @"Modification timestamp should roundtrip"); - XCTAssertTrue(res.expires, @"Request should have an expiration timestamp"); - XCTAssertEqual(MGLTimeIntervalFromDuration(res.expires->time_since_epoch()), floor(future.timeIntervalSince1970), @"Expiration timestamp should roundtrip"); - XCTAssertTrue(res.etag, @"Request should have an entity tag"); - XCTAssertEqual(*res.etag, "some etag", @"Entity tag should roundtrip"); - XCTAssertTrue(res.mustRevalidate, @"Request should require revalidation"); - XCTAssertEqual("test data", *res.data, @"Request did not return expected data"); - CFRunLoopStop(CFRunLoopGetCurrent()); - }); - + __block NSDate *now = [NSDate date]; + __block NSDate *future = [now dateByAddingTimeInterval:600]; + __block std::unique_ptr req; + [os preloadData:data forURL:styleURL modificationDate:now expirationDate:future eTag:@"some etag" mustRevalidate:YES completionHandler:^(NSURL * url, NSError * _Nullable error){ + XCTAssertFalse(error, @"preloadData should not return an error"); + XCTAssertEqual(styleURL, url, @"Preloaded resource url is invalid"); + + auto fs = os.mbglDatabaseFileSource; + const mbgl::Resource resource { mbgl::Resource::Unknown, "https://api.mapbox.com/some/thing1" }; + req = fs->request(resource, [&, tNow = now.timeIntervalSince1970, tFuture = future.timeIntervalSince1970](mbgl::Response res) { + XCTAssertFalse(res.error.get(), @"Request should not return an error"); + XCTAssertTrue(res.data.get(), @"Request should return data"); + XCTAssertTrue(res.modified, @"Request should have a modification timestamp"); + XCTAssertEqual(MGLTimeIntervalFromDuration(res.modified->time_since_epoch()), floor(tNow), @"Modification timestamp should roundtrip"); + XCTAssertTrue(res.expires, @"Request should have an expiration timestamp"); + XCTAssertEqual(MGLTimeIntervalFromDuration(res.expires->time_since_epoch()), floor(tFuture), @"Expiration timestamp should roundtrip"); + XCTAssertTrue(res.etag, @"Request should have an entity tag"); + XCTAssertEqual(*res.etag, "some etag", @"Entity tag should roundtrip"); + XCTAssertTrue(res.mustRevalidate, @"Request should require revalidation"); + XCTAssertEqual("test data", *res.data, @"Request did not return expected data"); + CFRunLoopStop(CFRunLoopGetCurrent()); + }); + }]; + CFRunLoopRun(); } +- (void)testSetMaximumAmbientCache { + XCTestExpectation *expectation = [self expectationWithDescription:@"Expect maximum cache size to be raised without an error."]; + [[MGLOfflineStorage sharedOfflineStorage] setMaximumAmbientCacheSize:0 withCompletionHandler:^(NSError * _Nullable error) { + XCTAssertNil(error); + [[MGLOfflineStorage sharedOfflineStorage] setMaximumAmbientCacheSize:50*1024*1024 withCompletionHandler:^(NSError * _Nullable error) { + XCTAssertNil(error); + [expectation fulfill]; + }]; + }]; + + [self waitForExpectationsWithTimeout:10 handler:nil]; +} + +- (void)testInvalidateAmbientCache { + XCTestExpectation *expectation = [self expectationWithDescription:@"Expect cache to be invalidated without an error."]; + [[MGLOfflineStorage sharedOfflineStorage] invalidateAmbientCacheWithCompletionHandler:^(NSError * _Nullable error) { + XCTAssertNil(error); + [expectation fulfill]; + }]; + [self waitForExpectationsWithTimeout:10 handler:nil]; +} + +- (void)testClearCache { + XCTestExpectation *expectation = [self expectationWithDescription:@"Expect cache to be cleared without an error."]; + [[MGLOfflineStorage sharedOfflineStorage] clearAmbientCacheWithCompletionHandler:^(NSError * _Nullable error) { + XCTAssertNil(error); + [expectation fulfill]; + }]; + [self waitForExpectationsWithTimeout:10 handler:nil]; +} + +- (void)testResetDatabase { + XCTestExpectation *expectation = [self expectationWithDescription:@"Expect database to be reset without an error."]; + [[MGLOfflineStorage sharedOfflineStorage] resetDatabaseWithCompletionHandler:^(NSError * _Nullable error) { + XCTAssertNil(error); + [expectation fulfill]; + }]; + [self waitForExpectationsWithTimeout:10 handler:nil]; +} + @end diff --git a/platform/ios/CHANGELOG.md b/platform/ios/CHANGELOG.md index 26ebe31c6..bd3df88dc 100644 --- a/platform/ios/CHANGELOG.md +++ b/platform/ios/CHANGELOG.md @@ -20,6 +20,7 @@ Mapbox welcomes participation and contributions from everyone. Please read [CONT * Fixed issues where an offline pack would stop downloading before completion. ([#16230](https://github.com/mapbox/mapbox-gl-native/pull/16230), [#16240](https://github.com/mapbox/mapbox-gl-native/pull/16240)) * When an offline pack encounters an HTTP 404 error, the `MGLOfflinePackUserInfoKeyError` user info key of the `MGLOfflinePackErrorNotification` now indicates the resource that could not be downloaded. ([#16240](https://github.com/mapbox/mapbox-gl-native/pull/16240)) * Fixed a memory leak when zooming with any options enabled in the `MGLMapView.debugMask` property. ([#15179](https://github.com/mapbox/mapbox-gl-native/issues/15179)) +* Added the `-[MGLOfflineStorage preloadData:forURL:modificationDate:expirationDate:eTag:mustRevalidate:completionHandler:]` method for determining when the data is ready to retrieve from the cache. ([#188](https://github.com/mapbox/mapbox-gl-native-ios/pull/188)) ## 5.7.0 - February 13, 2020 diff --git a/platform/macos/CHANGELOG.md b/platform/macos/CHANGELOG.md index cbca9374b..504c49d73 100644 --- a/platform/macos/CHANGELOG.md +++ b/platform/macos/CHANGELOG.md @@ -51,6 +51,7 @@ * Fixed issues where an offline pack would stop downloading before completion. ([#16230](https://github.com/mapbox/mapbox-gl-native/pull/16230), [#16240](https://github.com/mapbox/mapbox-gl-native/pull/16240)) * When an offline pack encounters an HTTP 404 error, the `MGLOfflinePackUserInfoKeyError` user info key of the `MGLOfflinePackErrorNotification` now indicates the resource that could not be downloaded. ([#16240](https://github.com/mapbox/mapbox-gl-native/pull/16240)) * Expired resources are now fetched at a lower priority than new resources. ([#15950](https://github.com/mapbox/mapbox-gl-native/pull/15950)) +* Added the `-[MGLOfflineStorage preloadData:forURL:modificationDate:expirationDate:eTag:mustRevalidate:completionHandler:]` method for determining when the data is ready to retrieve from the cache. ([#188](https://github.com/mapbox/mapbox-gl-native-ios/pull/188)) ### Other changes