2015-10-02 15 views
0

我的應用程序頁面有一個表單,我希望用戶輸入他的名字和電話號碼。我想在NSURL中插入一個字符串中的變量(Swift)

我想將這些數據提取到下面的URL中。

變量是用戶名,phoneno。

var url:NSURL = NSURL(string: "https:xyz.com/newRequest?fullname=\(username)&phone=\(phoneno)")!

這是與用戶名和PhoneNumber參數變量寫URL正確的語法。


這就是我想實現,但在模擬過程中我不斷收到錯誤405 -

var post:NSString = "username=\(username)&phoneno=\(phoneno)" 

NSLog("PostData: %@",post); 

var url:NSURL = NSURL(string: "https://example.com/newRequest?fullname=(username)&phone=(phoneno)")! 

var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! 

var postLength:NSString = String(postData.length) 

var request:NSMutableURLRequest = NSMutableURLRequest(URL: url) 
request.HTTPMethod = "POST" 
request.HTTPBody = postData 
request.setValue(postLength, forHTTPHeaderField: "Content-Length") 
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 
request.setValue("application/json", forHTTPHeaderField: "Accept") 
+0

您忘記了源代碼示例中的反斜槓。 – MirekE

+0

我只是不知道如何使用url字符串中的變量組件... –

回答

1

你應該使用NSURLComponentsNSURLQueryItem代替。那麼系統可以正確地爲你逃避價值。像這樣:

let username = "foo" 
let phoneno = "bar" 

let comps = NSURLComponents(string: "https://example.com/newRequest") 
comps?.queryItems = [ 
    NSURLQueryItem(name: "fullname", value: username), 
    NSURLQueryItem(name: "phone", value: phoneno) 
] 

comps?.URL // returns https://example.com/newRequest?fullname=foo&phone=bar 
+0

謝謝!你可以幫我做些什麼改變。我剛開始使用Swift和JSON像2天,我仍然不確定自己在做什麼:D –

+0

添加了一個示例。 – jtbandes

+0

謝謝。 那麼現在我不需要使用NSLog,NSData或任何後續的請求語句? –