2012-08-09 15 views
11

Io uso questa riga di codice per caricare un file HTML locale in una vista web:NSURL aggiungere parametri per il metodo fileURLWithPath

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"html"]]; 

Tuttavia voglio aggiungere alcuni parametri HTTP all'URL senza fortuna finora.

Ho provato questo:

url = [url URLByAppendingPathComponent:@"?param1=1"]; 

Ma dopo questo un HTML non caricare in WebView.

C'è un modo per caricare il file html locale in webview con params?

+0

Se "NSlog" l'URL dopo aver aggiunto i parametri sono inclusi? – rckoenes

risposta

13

fare questo:

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"html"]]; 

NSString *URLString = [url absoluteString]; 
NSString *queryString = @"?param1=1"; 
NSString *URLwithQueryString = [URLString stringByAppendingString: queryString]; 

NSURL *finalURL = [NSURL URLWithString:URLwithQueryString]; 
NSURLRequest *request = [NSURLRequest requestWithURL:finalURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:(NSTimeInterval)10.0 ]; 

[web loadRequest:request]; 
+0

Ecco fatto. Grazie! –

+1

Ho bisogno di un pulsante di voto +50 per questa risposta. – DataGraham

+0

Questo non sempre funziona. Se l'URL termina con i frammenti (ad esempio #qualcosa), diventa un URL non valido dopo aver eseguito questa parte di codice. –

1

Io lo uso come questo senso:

NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"xml"]]; 

Se il file incluso nella cartella delle risorse del Navigatore progetto. in caso contrario, è necessario impostare il percorso completo in NSString e utilizzarlo nel percorso NSURL.

6

La risposta più aggiornata di Prince non funziona sempre.

In iOS 7 Apple ha introdotto la classe NSURLComponents, che possiamo sfruttare per aggiungere in modo sicuro una query a NSURL.

NSURL *contentURL = ...; 
NSURLComponents *components = [[NSURLComponents alloc] initWithURL:contentURL resolvingAgainstBaseURL:NO]; 
NSMutableArray *queryItems = [components.queryItems mutableCopy]; 
if (!queryItems) queryItems = [[NSMutableArray alloc] init]; 
[queryItems addObject:[NSURLQueryItem queryItemWithName:@"access_token" value:@"token_here"]]; 
components.queryItems = queryItems; 
NSURL *newURL = components.URL; 
+0

Grazie, esattamente quello che stavo cercando –

+0

Una nota qui: la proprietà queryItems di NSURLComponents è disponibile solo in iOS 8+ –

Problemi correlati