2013-02-26 46 views
6

我開發在該應用程序,我需要在同一時間在NSURL傳遞多個參數 我的代碼,一個應用程序是如何在iOS中傳遞NSURL字符串中的多個參數?

responseData = [[NSMutableData data] retain]; 
ArrData = [NSMutableArray array]; 
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://rate-exchange.appspot.com/currency?from=%@&to=%@&q=%@",strfrom,strto,strgo]]; 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; 
//NSURLRequest *request1 = [NSURLRequest requestWithURL: 
//[NSURL URLWithString:@"http://rate-exchange.appspot.com/currency?from=%@&to=%@&q=1",strfrom,strto]]; 

上面的代碼,我需要動態傳遞多個參數。可能嗎 ?如果是,那麼怎麼樣? 感謝&問候

+1

嘗試創建一個單獨的字符串添加到URL像'NSSString之前*海峽= [NSString stringWithFormat:@「http://rate-exchange.appspot.com/currency?from=%@&to=%@&q=%@」,strfrom,strto,strgo]',然後將此str添加到URL – nsgulliver 2013-02-26 12:23:19

+0

首先將所有參數傳遞給NSString,然後將最終字符串分配給NSURL。 – jamil 2013-02-26 12:24:08

+0

我不能完全理解你的問題。你仍然在你的問題中傳遞多個參數 – Warewolf 2013-02-26 12:40:46

回答

5

嘗試添加到URL類似

NSSString *strURL=[NSString stringWithFormat:@"http://rate-exchange.appspot.com/currency?from=%@&to=%@&q=%@"‌​,strfrom,strto,strgo]; 

,然後之前創建一個單獨的字符串添加這個strURL中的URL

NSURL *url = [NSURL URLWithString:strURL]; 

最後將其添加到請求,你的代碼是錯誤的地方你添加網址請求,URL不是一個字符串它是一個URL所以它應該是requestWithURL不是URLWithString,它應該是這樣的

NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
+1

完美解決方案.....謝謝你nsgulliver – areddy 2013-02-26 13:18:44

+0

歡迎你areddy! – nsgulliver 2013-02-26 13:19:40

1

有一件事許多這些答案的缺失是利用[NSString stringByAddingPercentEscapesUsingEncoding:],以避免在URL中使用無效字符:

NSString *baseURL = [NSString stringWithFormat:@"http://rate-exchange.appspot.com/currency?from=%@&to=%@&q=%@",strfrom,strto,strgo]; 
NSURL *url = [NSURL URLWithString:[baseURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
+0

這是一個很好的觀點,但請注意,stringByAddingPercentEscapesUsingEncoding並未完全對您的字符串進行網址編碼。它忽略了諸如/和&的東西。 stackoverflow有一堆如何使你自己的例子。 – 2013-07-31 15:30:15

+0

但是,對我而言,trojanfoe的答案是發送unicode單詞作爲URL一部分的一個組成部分。所以給他+1。 – 2014-11-02 21:51:21

相關問題