从这个URL中提取一些元素的最简单方法是什么

时间:2013-02-25 04:41:59

标签: objective-c cocoa url

这是网址

assets-library://asset/asset.JPG?id=CF2AF034-9CF7-4472-9185-5EEFA1614A07&ext=JPG

我想得到:

CF2AF034-9CF7-4472-9185-5EEFA1614A07

我该怎么做? NSURL中是否有可以实现此目的的方法?

这就是我所做的:

-(NSString *) fgetTokenWithPre:(NSString *) pre andPost:(NSString*) post startSearch:(NSUInteger) start
{
NSRange rangeToSearch;
rangeToSearch.location = start;
rangeToSearch.length =self.length-rangeToSearch.location;

NSRange preRange = [self rangeOfString:self options:NSCaseInsensitiveSearch range:rangeToSearch];

结果

(lldb) po self
$6 = 0x1e54f130 id=00000000-0000-0000-0000-0000000005E9&ext=JPG
(lldb) po pre
$7 = 0x0021d8a0 id=
(lldb) p preRange
(NSRange) $8 = location=0, length=47

但这没有意义。很明显,自我是47长度,我正在寻找只有3长度的前期。那么preRange怎么会是[0,47]?

2 个答案:

答案 0 :(得分:0)

以下代码块可能会执行您之后的操作

__block NSString *queryID;
[[[url query] componentsSeparatedByString:@"&"] enumerateObjectsUsingBlock:^(NSString *queryString, NSUInteger idx, BOOL *stop) {
  NSArray *query = [queryString componentsSeparatedByString:@"="];
  if ([query[0] isEqualToString:@"id"]) {
    queryID = query[1];
    *stop = YES;
  }
}];

NSLog(@"ID value = %@", queryID);

但是,它不是很安全。它假设关于格式良好的URL,并且query数组中将存在(至少)2个值。

答案 1 :(得分:0)

NSUrl *asseturl = [NSURL URLWithString:@"assets-library://asset/asset.JPG?id=CF2AF034-9CF7-4472-9185-5EEFA1614A07&ext=JPG"];


ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
    ALAssetRepresentation *rep = [myasset defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];
    if (iref) {
        largeimage = [UIImage imageWithCGImage:iref];
        [largeimage retain];
    }
};

//
ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
{
    NSLog(@"booya, cant get image - %@",[myerror localizedDescription]);
};

if(mediaurl && [mediaurl length] && ![[mediaurl pathExtension] isEqualToString:AUDIO_EXTENSION])
{
    [largeimage release];
    NSURL *asseturl = [NSURL URLWithString:mediaurl];
    ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
    [assetslibrary assetForURL:asseturl 
                   resultBlock:resultblock
                  failureBlock:failureblock];
}

}