1

我正在处理字符串,但有一个小问题我不明白。事实上,我有一个这样的字符串:"ALAsset - Type:Photo, URLs:assets-library://asset/asset.JPG?id=168BA548-9C81-4B08-B69C-B775E5DD9341&ext=JPG"我需要找到"URLs:" and "?id=". 为此,我正在尝试使用NSRange. 在这种模式下,我给出了我需要的第一个索引和最后一个索引,但它似乎不起作用。这是我的代码:

NSString *description = [asset description];
NSRange first = [description rangeOfString:@"URLs:"];
NSRange second = [description rangeOfString:@"?id="];
NSString *path = [description substringWithRange: NSMakeRange(first.location, second.location)];

它返回给我这种字符串:"URLs:assets-library://asset/asset.JPG?id=168BA548-9C81-4B08-B69C-B775E5DD9341&ext=JPG". 这是对的吗?我期待获得"assets-library://asset/asset.JPG" string. 我在哪里做错了?有一个更好的方法吗?我已按照此网址寻求帮助:http://www.techotopia.com/index.php/Working_with_String_Objects_in_Objective-C

谢谢

4

3 回答 3

3

试试这个范围: NSMakeRange(first.location + first.length, second.location - (first.location + first.length))

于 2013-08-26T07:37:10.390 回答
2

不要解析ALAsset描述字符串!如果描述改变了你的代码就会中断。使用方法ALAssetNSURL为您提供。首先,通过方法获取 URL 的字典(按资产类型映射)valueForProperty:。然后,对于每个 URL,获取absoluteString并从中删除查询字符串。我通过将以下代码放入application:didFinishLaunchingWithOptions:单视图 iPhone 应用程序模板的方法中得到了您要查找的字符串。

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
   [group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop) {
       NSDictionary *URLDictionary = [asset valueForProperty:ALAssetPropertyURLs];
       for (NSURL *URL in [URLDictionary allValues]) {
           NSString *URLString = [URL absoluteString];
           NSString *query = [URL query];
           if ([query length] > 0) {
               NSString *toRemove = [NSString stringWithFormat:@"?%@",query];
               URLString = [URLString stringByReplacingOccurrencesOfString:toRemove withString:@""];
               NSLog(@"URLString = %@", URLString);
           }
       }
   }];
} failureBlock:^(NSError *error) {

}];
于 2013-08-26T08:14:07.540 回答
1
NSRange first = [description rangeOfString:@"URLs:"];

为您提供 的位置U,因此您需要first.location+5获取 的起始位置assets-library

NSRangeMake(loc,len)需要一个起始位置loc和一个长度,因此您需要使用second.location-first.location-5来获取您正在寻找的长度。

全部加起来,将最后一行替换为:

NSRange r = NSMakeRange(first.location+5, second.location-first.location-5);
NSString *path = [description substringWithRange:r];
于 2013-08-26T07:36:19.637 回答