我有一个包含 ALAsset url 的数组(不是完整的 ALAsset 对象)所以每次我启动我的应用程序时,我都想检查我的数组,看看它是否仍然是最新的......
所以我尝试了
NSData *assetData = [[NSData alloc] initWithContentsOfFile:@"assets-library://asset/asset.PNG?id=1000000001&ext=PNG"];
但是assetData总是为零
谢谢帮助
我有一个包含 ALAsset url 的数组(不是完整的 ALAsset 对象)所以每次我启动我的应用程序时,我都想检查我的数组,看看它是否仍然是最新的......
所以我尝试了
NSData *assetData = [[NSData alloc] initWithContentsOfFile:@"assets-library://asset/asset.PNG?id=1000000001&ext=PNG"];
但是assetData总是为零
谢谢帮助
使用 ALAssetsLibrary 的assetForURL:resultBlock:failureBlock: 方法从其 URL 获取资产。
// Create assets library
ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease];
// Try to load asset at mediaURL
[library assetForURL:mediaURL resultBlock:^(ALAsset *asset) {
// If asset exists
if (asset) {
// Type your code here for successful
} else {
// Type your code here for not existing asset
}
} failureBlock:^(NSError *error) {
// Type your code here for failure (when user doesn't allow location in your app)
}];
拥有资产路径,您可以使用此功能检查图像是否存在:
-(BOOL) imageExistAtPath:(NSString *)assetsPath
{
__block BOOL imageExist = NO;
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:[NSURL URLWithString:assetsPath] resultBlock:^(ALAsset *asset) {
if (asset) {
imageExist = YES;
}
} failureBlock:^(NSError *error) {
NSLog(@"Error %@", error);
}];
return imageExist;
}
请记住,检查图像是否存在是检查异步。如果你想等到新线程在主线程中完成他的生命调用函数“imageExistAtPath”:
dispatch_async(dispatch_get_main_queue(), ^{
[self imageExistAtPath:assetPath];
});
或者您可以使用信号量,但这不是很好的解决方案:
-(BOOL) imageExistAtPath:(NSString *)assetsPath
{
__block BOOL imageExist = YES;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(queue, ^{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:[NSURL URLWithString:assetsPath] resultBlock:^(ALAsset *asset) {
if (asset) {
dispatch_semaphore_signal(semaphore);
} else {
imageExist = NO;
dispatch_semaphore_signal(semaphore);
}
} failureBlock:^(NSError *error) {
NSLog(@"Error %@", error);
}];
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return imageExist;
}
对于 iOS 8 或更高版本,有一个同步方法来检查是否ALAsset
存在。
@import Photos;
if ([PHAsset fetchAssetsWithALAssetURLs:@[assetURL] options:nil].count) {
// exist
}
迅速:
import Photos
if PHAsset.fetchAssetsWithALAssetURLs([assetURL], options: nil).count > 0 {
// exist
}
斯威夫特 3:
import Photos
if PHAsset.fetchAssets(withALAssetURLs: [assetURL], options: nil).count > 0 {
// exist
}
使用此方法检查文件是否存在
NSURL *yourFile = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:@"YourFileHere.txt"];
if ([[NSFileManager defaultManager]fileExistsAtPath:storeFile.path
isDirectory:NO]) {
NSLog(@"The file DOES exist");
} else {
NSLog(@"The file does NOT exist");
}