標籤:else dba 分享 nbsp operation nts 輸入框 send usr
移動client往往須要同後台server進行通訊,上傳或者下載資料,最經常使用到的方式就是Http Get,如今我們來學習在iOS項目中使用Get方式同server進行通訊。
【一】server端實現
(1)首先要安裝好能進行J2EE開發的Eclipse或者MyEclipse,配置好Tomcat環境。
我這裡使用Eclipse Mars。Tomcat版本號碼為8. 然後建立一個Dynamic Web Project。名稱為MyServer。
然後在WebContent中建立一個JSP File。名稱為index.當前檔案夾結構例如以下:
。
(2)然後在Hello.jsp中實現例如以下:對於client的請求,我將會返回“Hello 名字”。否則返回No Paras.
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%String name = request.getParameter("name");if (name != null) {out.print("Hello " + name);} else {out.print("No Paras");}%>
(3)直接點擊執行,或者在瀏覽器中輸入url,結果例如以下:
。
【二】iOSclient實現
(1)建立一個iOS項目。Language選擇Swift。然後在storyboard中設計介面例如以下:
。
(2)然後分別進行控制項和代碼的綁定。輸入框TextField和顯示返回結果的TextView進行Outlets綁定,發送button進行Action綁定。最後實現代碼例如以下:
@IBOutlet weak var inputName: UITextField! @IBOutlet weak var feedbackInfo: UITextView! override func viewDidLoad() { super.viewDidLoad() } @IBAction func connectServer(sender: UIButton) { NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: NSURL(string: "http://localhost:8080/MyServer/Hello.jsp?name=\(inputName.text)")!), queue: NSOperationQueue()) { (resp:NSURLResponse!, data:NSData!, error:NSError!) -> Void in if let d = data{ dispatch_sync(dispatch_get_main_queue(), { () -> Void in self.feedbackInfo.text = String(NSString(data: d, encoding: NSUTF8StringEncoding)!) }) } } }
當中button的點擊事件也能夠是以下的形式:
@IBAction func connectServer(sender: UIButton) { NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: NSURL(string: "http://localhost:8080/MyServer/Hello.jsp?name=\(inputName.text)")!), queue: NSOperationQueue.mainQueue()) { (resp:NSURLResponse!, data:NSData!, error:NSError!) -> Void in if let d = data{ self.feedbackInfo.text = String(NSString(data: d, encoding: NSUTF8StringEncoding)!) } } }
(3)執行程式。實現效果例如以下:
.
github首頁:https://github.com/chenyufeng1991 。歡迎大家訪問!
iOS項目開發實戰——通過Http Get方式與server通訊