2013-02-25 86 views
-2

這種提取一些元素的最簡單的方法就是URL什麼是從這個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]?

+0

http://stackoverflow.com/search?q=%5Bobjc%5D+extract+url:[提取URL的一部分(http://stackoverflow.com/q/3308681 ),[解析nsurl查詢屬性](http://stackoverflow.com/q/3997976),[如何提取url的方案和主機?](http://stackoverflow.com/q/8890475) – 2013-02-25 04:43:22

回答

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個值。

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]; 
} 

}