NSURL tirare fuori un singolo valore per una chiave in una stringa di parametri
-
19-09-2019 - |
Domanda
Ho un NSURL:
serverCall? X = y = a & b & z = c
Qual è il modo più rapido ed efficiente per ottenere il valore di y?
Grazie
Soluzione
UPDATE:
Dal 2010, quando questo è stato scritto, sembra che Apple ha rilasciato una serie di strumenti a tal fine. Si prega di vedere le risposte qui sotto per quelli.
Old School-Solution:
So bene che hai detto " il modo più rapido " ma dopo che ho iniziato a fare un test con NSScanner
non riuscivo a smettere. E mentre non è la via più breve, è sicuro a portata di mano se avete intenzione di utilizzare questa funzione molto. Ho creato una classe URLParser
che ottiene questi Vars utilizzando un NSScanner
. L'utilizzo è semplice come:
URLParser *parser = [[[URLParser alloc] initWithURLString:@"http://blahblahblah.com/serverCall?x=a&y=b&z=c&flash=yes"] autorelease];
NSString *y = [parser valueForVariable:@"y"];
NSLog(@"%@", y); //b
NSString *a = [parser valueForVariable:@"a"];
NSLog(@"%@", a); //(null)
NSString *flash = [parser valueForVariable:@"flash"];
NSLog(@"%@", flash); //yes
E la classe che fa questo è il seguente (* file di origine nella parte inferiore del post):
URLParser.h
@interface URLParser : NSObject {
NSArray *variables;
}
@property (nonatomic, retain) NSArray *variables;
- (id)initWithURLString:(NSString *)url;
- (NSString *)valueForVariable:(NSString *)varName;
@end
URLParser.m
@implementation URLParser
@synthesize variables;
- (id) initWithURLString:(NSString *)url{
self = [super init];
if (self != nil) {
NSString *string = url;
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"&?"]];
NSString *tempString;
NSMutableArray *vars = [NSMutableArray new];
[scanner scanUpToString:@"?" intoString:nil]; //ignore the beginning of the string and skip to the vars
while ([scanner scanUpToString:@"&" intoString:&tempString]) {
[vars addObject:[tempString copy]];
}
self.variables = vars;
[vars release];
}
return self;
}
- (NSString *)valueForVariable:(NSString *)varName {
for (NSString *var in self.variables) {
if ([var length] > [varName length]+1 && [[var substringWithRange:NSMakeRange(0, [varName length]+1)] isEqualToString:[varName stringByAppendingString:@"="]]) {
NSString *varValue = [var substringFromIndex:[varName length]+1];
return varValue;
}
}
return nil;
}
- (void) dealloc{
self.variables = nil;
[super dealloc];
}
@end
* se non ti piace copiare e incollare si può solo scaricare i file di origine - ho fatto un post veloce blog su questo qui .
Altri suggerimenti
Tante parser URL personalizzato qui, ricordate NSURLComponents è tuo amico!
Ecco un esempio in cui tiro fuori un parametro URL codificato per "pagina"
Swift
let myURL = "www.something.com?page=2"
var pageNumber : Int?
if let queryItems = NSURLComponents(string: myURL)?.queryItems {
for item in queryItems {
if item.name == "page" {
if let itemValue = item.value {
pageNumber = Int(itemValue)
}
}
}
}
print("Found page number: \(pageNumber)")
Objective-C
NSString *myURL = @"www.something.com?page=2";
NSURLComponents *components = [NSURLComponents componentsWithString:myURL];
NSNumber *page = nil;
for(NSURLQueryItem *item in components.queryItems)
{
if([item.name isEqualToString:@"page"])
page = [NSNumber numberWithInteger:item.value.integerValue];
}
"Perché reinventare la ruota!" - Qualcuno intelligente
Sono abbastanza sicuro che si deve analizzare da soli. Tuttavia, non è troppo male:
NSString * q = [myURL query];
NSArray * pairs = [q componentsSeparatedByString:@"&"];
NSMutableDictionary * kvPairs = [NSMutableDictionary dictionary];
for (NSString * pair in pairs) {
NSArray * bits = [pair componentsSeparatedByString:@"="];
NSString * key = [[bits objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString * value = [[bits objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[kvPairs setObject:value forKey:key];
}
NSLog(@"y = %@", [kvPairs objectForKey:@"y"]);
In Swift è possibile utilizzare NSURLComponents per analizzare la stringa di query di una NSURL in un [ANYOBJECT].
È quindi possibile creare un dizionario da esso (o accedere agli elementi direttamente) per ottenere le coppie chiave / valore. A titolo di esempio, questo è quello che sto usando per analizzare un NSURL url variabile:
let urlComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)
let items = urlComponents?.queryItems as [NSURLQueryItem]
var dict = NSMutableDictionary()
for item in items{
dict.setValue(item.value, forKey: item.name)
}
println(dict["x"])
Ho usato questa Categoria:. https://github.com/carlj/NSURL-Parameters
E 'piccolo e facile da usare:
#import "NSURL+Parameters.h"
...
NSURL *url = [NSURL URLWithString:@"http://foo.bar.com?paramA=valueA¶mB=valueB"];
NSString *paramA = url[@"paramA"];
NSString *paramB = url[@"paramB"];
È possibile utilizzare Google Toolbox per Mac. Si aggiunge una funzione per NSString per convertire stringa di query a un dizionario.
http://code.google.com/p/google-toolbox -per-mac /
Funziona come un fascino
NSDictionary * d = [NSDictionary gtm_dictionaryWithHttpArgumentsString:[[request URL] query]];
Ecco un 2.0 estensione Swift che fornisce semplice accesso ai parametri:
extension NSURL {
var params: [String: String] {
get {
let urlComponents = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)
var items = [String: String]()
for item in urlComponents?.queryItems ?? [] {
items[item.name] = item.value ?? ""
}
return items
}
}
}
Utilizzo di esempio:
let url = NSURL(string: "http://google.com?test=dolphins")
if let testParam = url.params["test"] {
print("testParam: \(testParam)")
}
ho scritto una categoria semplice per estendere NSString / NSURL che ti permette di estrarre i parametri di query URL singolarmente o come un dizionario di coppie chiave / valore:
L'ho fatto usando un metodo categoria sulla base di soluzione @Dimitris
#import "NSURL+DictionaryValue.h"
@implementation NSURL (DictionaryValue)
-(NSDictionary *)dictionaryValue
{
NSString *string = [[self.absoluteString stringByReplacingOccurrencesOfString:@"+" withString:@" "]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"&?"]];
NSString *temp;
NSMutableDictionary *dict = [[[NSMutableDictionary alloc] init] autorelease];
[scanner scanUpToString:@"?" intoString:nil]; //ignore the beginning of the string and skip to the vars
while ([scanner scanUpToString:@"&" intoString:&temp])
{
NSArray *parts = [temp componentsSeparatedByString:@"="];
if([parts count] == 2)
{
[dict setObject:[parts objectAtIndex:1] forKey:[parts objectAtIndex:0]];
}
}
return dict;
}
@end
Si può fare facile:
- (NSMutableDictionary *) getUrlParameters:(NSURL *) url
{
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
NSString *tmpKey = [url query];
for (NSString *param in [[url query] componentsSeparatedByString:@"="])
{
if ([tmpKey rangeOfString:param].location == NSNotFound)
{
[params setValue:param forKey:tmpKey];
tmpKey = nil;
}
tmpKey = param;
}
[tmpKey release];
return params;
}
E 'tornare dizionario simile al primo: chiave = valore
Ho modificato il codice di Dimitris' un po 'per una migliore gestione della memoria e l'efficienza. Inoltre, funziona in ARC.
URLParser.h
@interface URLParser : NSObject
- (void)setURLString:(NSString *)url;
- (NSString *)valueForVariable:(NSString *)varName;
@end
URLParser.m
#import "URLParser.h"
@implementation URLParser {
NSMutableDictionary *_variablesDict;
}
- (void)setURLString:(NSString *)url {
[_variablesDict removeAllObjects];
NSString *string = url;
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"&?"]];
NSString *tempString;
[scanner scanUpToString:@"?" intoString:nil]; //ignore the beginning of the string and skip to the vars
while ([scanner scanUpToString:@"&" intoString:&tempString]) {
NSString *dataString = [tempString copy];
NSArray *sepStrings = [dataString componentsSeparatedByString:@"="];
if ([sepStrings count] == 2) {
[_variablesDict setValue:sepStrings[1] forKeyPath:sepStrings[0]];
}
}
}
- (id)init
{
self = [super init];
if (self) {
_variablesDict = [[NSMutableDictionary alloc] init];
}
return self;
}
- (NSString *)valueForVariable:(NSString *)varName {
NSString *val = [_variablesDict valueForKeyPath:varName];
return val;
return nil;
}
-(NSString *)description {
return [NSString stringWithFormat:@"Current Variables: %@", _variablesDict];
}
@end
Tutte le risposte attuali sono la versione specifica o inutilmente dispendioso. Perchè creare un dizionario, se si desidera solo un valore?
Ecco un semplice risposta che supporta tutte le versioni di iOS:
- (NSString *)getQueryParam:(NSString *)name fromURL:(NSURL *)url
{
if (url)
{
NSArray *urlComponents = [url.query componentsSeparatedByString:@"&"];
for (NSString *keyValuePair in urlComponents)
{
NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
if ([key isEqualToString:name])
{
return [[pairComponents lastObject] stringByRemovingPercentEncoding];
}
}
}
return nil;
}
più veloce è il seguente:
NSString* x = [url valueForQueryParameterKey:@"x"];