12

NSURLのコンポーネントを解析するための標準のオブジェクトまたは関数はありますか?明らかに私はそれを書くことができましたが、なぜ車輪を再発明するのですか?

[NSURL path] 私がむしろ取り戻したいのは、次のNSStringように入力された辞書です。"argX=x&argY=y&argZ=z"{@"argX" => @"x", @"argY" => @"y", @"argZ" = @"z"}

「/partA/ partB / partC」のような文字列を返すパスの場合、構造を持つ配列を取得したいと思います{[0] => @"partA", [1] => @"partB", [2] => @"partC"}

これはかなり具体的な質問だと思いますが、多くの人が望んでいるようです。

これはiOS用です!どうやらNSURLはmacOSで異なる機能を持っています。

4

6 に答える 6

12

了解しました。私は腹を立てて、カテゴリを介してNSStringを拡張するためのソリューションを作成しました。これはまだテストしていませんが、使用したい場合は試してみてください。

@interface NSString (ParseCategory)
- (NSMutableDictionary *)explodeToDictionaryInnerGlue:(NSString *)innerGlue outterGlue:(NSString *)outterGlue;
@end

@implementation NSString (ParseCategory)

- (NSMutableDictionary *)explodeToDictionaryInnerGlue:(NSString *)innerGlue outterGlue:(NSString *)outterGlue {
    // Explode based on outter glue
    NSArray *firstExplode = [self componentsSeparatedByString:outterGlue];
    NSArray *secondExplode;

    // Explode based on inner glue
    NSInteger count = [firstExplode count];
    NSMutableDictionary *returnDictionary = [NSMutableDictionary dictionaryWithCapacity:count];
    for (NSInteger i = 0; i < count; i++) {
        secondExplode = [(NSString *)[firstExplode objectAtIndex:i] componentsSeparatedByString:innerGlue];
        if ([secondExplode count] == 2) {
            [returnDictionary setObject:[secondExplode objectAtIndex:1] forKey:[secondExplode objectAtIndex:0]];
        }
    }

    return returnDictionary;
}

@end

それはこのように呼ばれます:

NSMutableDictionary *parsedQuery = [[myNSURL query] explodeToDictionaryInnerGlue:@"=" outterGlue=@"&"]

NSURLのパス部分(つまり、@ "/ partA / partB / partC")を解析するには、次のように呼び出します。

NSArray *parsedPath = [[nyNSURL path] componentsSeperatedByString:@"/"];

/!が先頭にあるため、parsedPath[0]は空の文字列になることに注意してください。

編集-これはあなたの使用の喜びのためのNSURLへのカテゴリー拡張です。最初の「/」を削除して、空の0インデックスがないようにします。

@implementation NSURL (ParseCategory)

- (NSArray *)pathArray {
    // Create a character set for the slash character
    NSRange slashRange;
    slashRange.location = (unsigned int)'/';
    slashRange.length = 1;
    NSCharacterSet *slashSet = [NSCharacterSet characterSetWithRange:slashRange];

    // Get path with leading (and trailing) slashes removed
    NSString *path = [[self path] stringByTrimmingCharactersInSet:slashSet];

    return [path componentsSeparatedByCharactersInSet:slashSet];
}

- (NSDictionary *)queryDictionary {
    NSDictionary *returnDictionary = [[[[self query] explodeToDictionaryInnerGlue:@"=" outterGlue:@"&"] copy] autorelease];
    return returnDictionary;
}

@end
于 2009-12-28T00:01:38.463 に答える
11

Sam Soffesは、NSURL/NSDictionaryの適切に管理されたカテゴリを作成しました。ここで見つけることができます:https ://github.com/samsoffes/sstoolkit/

于 2011-05-30T11:27:36.373 に答える
10

pathComponentsURLのコンポーネントの配列を返すものを確認することをお勧めします。詳細については、こちらをご覧ください。

于 2009-12-27T23:42:55.390 に答える
5

クエリ文字列を解析するために使用するものは次のとおりです

// Parse the individual parameters
// parameters = @"hello=world&foo=bar";
NSMutableDictionary *dictParameters = [[NSMutableDictionary alloc] init];
NSArray *arrParameters = [parameters componentsSeparatedByString:@"&"];
for (int i = 0; i < [arrParameters count]; i++) {
    NSArray *arrKeyValue = [[arrParameters objectAtIndex:i] componentsSeparatedByString:@"="];
    if ([arrKeyValue count] >= 2) {
        NSMutableString *strKey = [NSMutableString stringWithCapacity:0];
        [strKey setString:[[[arrKeyValue objectAtIndex:0] lowercaseString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
        NSMutableString *strValue   = [NSMutableString stringWithCapacity:0];
        [strValue setString:[[[arrKeyValue objectAtIndex:1]  stringByReplacingOccurrencesOfString:@"+" withString:@" "] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
        if (strKey.length > 0) [dictParameters setObject:strValue forKey:strKey];
    }
}
NSLog(@"Parameters: %@", dictParameters);
于 2011-12-08T09:53:20.020 に答える
2

作成することにした場合(必要なコンポーネントを取得するための既存のメソッドがあるかどうかはわかりません)、NSStringを使用することをお勧めしますcomponentsSeparatedByString

于 2009-12-27T23:41:10.713 に答える
2

iOS8およびOSX10.10で導入されたのはNSURLQueryItem、クエリの作成に使用できるです。NSURLQueryItemのドキュメントから:

NSURLQueryItemオブジェクトは、URLのクエリ部分にあるアイテムの単一の名前と値のペアを表します。NSURLComponentsオブジェクトのqueryItemsプロパティでクエリアイテムを使用します。

最初に以下を作成することにより、URLからクエリアイテムを取得できますNSURLComponents

NSURL *url = [NSURL URLWithString:@"http://stackoverflow.com?q=ios&count=10"];
NSURLComponents *components = [NSURLComponents componentsWithURL:url 
                                               resolvingAgainstBaseURL:YES];
for (NSURLQueryItem *item in components.queryItems) {
    NSLog(@"name: %@, value: %@", item.name, item.value);
}
// name: q, value: ios
// name: count, value: 10

の戻り値-queryItemsは辞書ではなく配列であることに注意してください。これは、以下が有効なURLであるためです。2つの同一の「キー」に注意してくださいfoo

http://google.com?foo=bar&foo=baz

クエリアイテムを介してURLを作成するには、指定された初期化子queryItemWithName:value:を使用し、それらをに追加してNSURLComponentsを生成しNSURLます。例えば:

NSString *urlString = @"http://stackoverflow.com";
NSURLComponents *components = [NSURLComponents componentsWithString:urlString];
NSURLQueryItem *search = [NSURLQueryItem queryItemWithName:@"q" value:@"ios"];
NSURLQueryItem *count = [NSURLQueryItem queryItemWithName:@"count" value:@"10"];
components.queryItems = @[ search, count ];
NSURL *url = components.URL; // http://stackoverflow.com?q=ios&count=10

疑問符とアンパサンドが自動的に処理されることに注意してください。NSURLパラメータの辞書からの作成は、次のように簡単です。

NSDictionary *queryDictionary = @{ @"q": @"ios", @"count": @"10" };
NSMutableArray *queryItems = [NSMutableArray array];
for (NSString *key in queryDictionary) {
    NSURLQueryItem *item = [NSURLQueryItem queryItemWithName:key 
                                                       value:queryDictionary[key]]; 
    [queryItems addObject:item];
}
components.queryItems = queryItems;

また、 NSURLQueryItemsを使用したNSURLの構築という詳細についてのブログ投稿も作成しました。

于 2015-07-28T13:14:16.950 に答える