上個月實在是太忙了,在系統上線的前幾天,業務人員還在不停的提新需求,真是醉了。上線那天晚上一直在出問題,熬到2點才搞定php
2015/12/12html
Day 47mysql
今天開始學習網絡編程ios
UIWebView程序員
■ UIWebView是iOS內置的瀏覽器控件,能夠瀏覽網頁、打開文檔等web
■ 可以加載html/htm、pdf、docx、txt等格式的文件sql
■ 系統自帶的Safari瀏覽器就是經過UIWebView實現的數據庫
UIWebView演練——加載百度首頁apache
很簡單,只要調用UIWebView的loadRequest方法便可,以下,編程
- (void)viewDidLoad { [super viewDidLoad]; [self loadURL:@"http://www.baidu.com"]; } - (void)loadURL:(NSString *)str { [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]]; }
值得一提的是,如今須要在info.plist中設置使用http請求
第一步:在plist中添加NSAppTransportSecurity項,此項爲NSDictionary
第二步:在NSAppTransportSecurity下添加
NSAllowsArbitraryLoads類型爲Boolean,value爲YES
蘋果正在加大應用安全的管控,這個舉措能夠看出蘋果對信息安全的重視,也暴露出大部分應用傳輸數據時都是未通過加密的,或使用私有方式加密,以致於蘋果開始對開發者提出要求。
私有加密雖然必定程度上是安全的,可是終究不是一個長久之計。應該早日使用HTTPS確保信息安全!
NSURL 肯定要訪問的網絡資源
NSURLRequest 創建網絡請求
而後配置本地服務器
經過命令行直接可使用諸如:C、C++、Python、Ruby、PHP、JavaScript、Perl等語言進行開發,Mac是程序員開發的利器
Mac系統中上不少程序員使用的工具和軟件都是經過命令行實現的,例如:Apache、SQLite、音頻格式轉換、視頻格式轉換、SVN、GIT……
判斷本地計算機的Apache服務器是否啓動
在瀏覽器地址欄中輸入:localhost
經過是否有返回結果,便可判斷本地的Apache是否正常工做
而後更改配置文件讓服務器支持php
在Mac中,若是要執行系統級命令,或者修改系統級文件,須要經過sudo命令來執行。須要先輸入管理員口令才能夠執行須要的命令
■ 啓動
sudo apachectl -k start
■ 從新啓動
sudo apachectl -k restart
PHP簡介
而後安裝mysql
2015/12/13
Day 48
昨天把服務器和數據庫都配置好了
今天學習 get&post請求
先在數據庫建表
drop table if exists userInfo;
create table userInfo (
id mediumint not null auto_increment primary key,
userName varchar(255) not null default '',
userPwd varchar(255) not null default '',
sex tinyint not null default 0,
userImage varchar(255) not null default '',
location varchar(255) not null default '',
description varchar(255) not null default '',
birthday varchar(255) not null default '',
email varchar(255) not null default '',
blog varchar(255) not null default '',
qq varchar(255) not null default '',
msn varchar(255) not null default ''
);
insert into userInfo (userName, userPwd) values ('yu3', '123456');
insert into userInfo (userName, userPwd) values ('zhangsan', 'zhang');
insert into userInfo (userName, userPwd) values ('lisi', 'li');
insert into userInfo (userName, userPwd) values ('wangwu', 'wang');
而後利用php發送請求,login.php內容以下
<?php class users { private $db; //構造函數 - 創建數據庫鏈接 function __construct() { $this->db = new mysqli('127.0.0.1', 'root', '123456', 'yu3'); if (mysqli_connect_errno()) { printf("鏈接錯誤:%s\n", mysqli_connect_error()); exit(); } $this->db->autocommit(FALSE); } //析構函數 - 關閉數據庫鏈接 function __destruct() { $this->db->close(); } //用戶登陸 function userLogin() { if (isset($_GET['username']) && isset($_GET['password'])) { //獲取參數 $accessType = '[GET]'; $userName = $_GET['username']; $userPassword = $_GET['password']; } else if (isset($_POST['username']) && isset($_POST['password'])) { //獲取參數 $accessType = '[POST]'; $userName = $_POST['username']; $userPassword = $_POST['password']; } else { echo('非法請求。'); return false; } //設置數據庫查詢字符編碼 $this->db->query('set names utf8'); //查詢請求 $data = $this->db->query("select id, userName, sex from userInfo where userName='$userName' and userPwd='$userPassword'"); //綁定查詢參數 $this->db->real_escape_string($userName); $this->db->real_escape_string($userPassword); //提交查詢請求 $this->db->commit(); //提取查詢結果 $row = $data->fetch_assoc(); //將查詢結果綁定到字典 $result = [ 'userId' => $row['id'], 'userName' => $row['userName'], 'sex' => $row['sex'] ]; //將字典使用JSON編碼 echo json_encode($result); return true; } } header('Content-Type:text/html;charset=utf-8'); $users = new users; $users->userLogin(); ?>
這樣在瀏覽器中發送請求以下,根據zhangsan密碼zhang能夠查出表裏的數據
簡歷工程,在storyboard裏,設置兩個textField輸入用戶名密碼,而後點擊按鈕放鬆請求,接收的數據在textView裏顯示
先發送get請求
NSLog(@"GET請求開始 %@",[NSThread currentThread]); NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login.php?username=%@&password=%@", self.userName.text, self.pwd.text]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]; NSLog(@"GET請求-NSURLRequest:%@ %@", request, [NSThread currentThread]); // Connection // 1> 登陸完成以前,不能作後續工做! // 2> 登陸進行中,能夠容許用戶乾點別的會更好! // 3> 讓登陸操做在其餘線程中進行,就不會阻塞主線程的工做 // 4> 結論:登錄也是異步訪問,中間須要阻塞住 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { if (connectionError == nil) { NSLog(@"response:%@ %@",response, [NSThread currentThread]); NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"返回的字符串:%@ - %@", str, [NSThread currentThread]); [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.responseText.text = str; NSLog(@「GET請求-更新UI %@",[NSThread currentThread]); }]; } NSLog(@"GET請求結束 %@", [NSThread currentThread]); }]; NSLog(@"GET請求-主線程其餘工做 %@", [NSThread currentThread]);
而後是post請求
NSLog(@"POST請求開始 %@",[NSThread currentThread]); NSString *urlStr = @"http://localhost/login.php"; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]]; //設置請求類型爲POST request.HTTPMethod = @"POST"; NSString *str = [NSString stringWithFormat:@"username=%@&password=%@", self.userName.text, self.pwd.text]; request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding]; NSLog(@"POST請求-NSMutableURLRequest:%@ %@", request, [NSThread currentThread]); [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { if (connectionError == nil) { NSLog(@"response:%@ %@",response, [NSThread currentThread]); NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"返回的字符串:%@ - %@", str, [NSThread currentThread]); [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.responseText.text = str; NSLog(@"更新UI %@",[NSThread currentThread]); }]; } NSLog(@"POST請求結束 %@", [NSThread currentThread]); }]; NSLog(@"POST請求-主線程其餘工做 %@", [NSThread currentThread]);
ios9.0之後蘋果建議咱們使用NSURLSession
NSURLConnection 做爲 Core Foundation / CFNetwork 框架的 API 之上的一個抽象,在 2003 年,隨着初版的 Safari 的發佈就發佈了。NSURLConnection 這個名字,其實是指代的 Foundation 框架的 URL 加載系統中一系列有關聯的組件:NSURLRequest、NSURLResponse、NSURLProtocol、 NSURLCache、 NSHTTPCookieStorage、NSURLCredentialStorage 以及同名類 NSURLConnection。
NSURLRequest 被傳遞給 NSURLConnection。被委託對象(遵照之前的非正式協議 <NSURLConnectionDelegate> 和<NSURLConnectionDataDelegate>)異步地返回一個 NSURLResponse 以及包含服務器返回信息的 NSData。
在一個請求被髮送到服務器以前,系統會先查詢共享的緩存信息,而後根據策略(policy)以及可用性(availability)的不一樣,一個已經被緩存的響應可能會被當即返回。若是沒有緩存的響應可用,則這個請求將根據咱們指定的策略來緩存它的響應以便未來的請求可使用。
在把請求發送給服務器的過程當中,服務器可能會發出鑑權查詢(authentication challenge),這能夠由共享的 cookie 或機密存儲(credential storage)來自動響應,或者由被委託對象來響應。發送中的請求也能夠被註冊的 NSURLProtocol 對象所攔截,以便在必要的時候無縫地改變其加載行爲。
無論怎樣,NSURLConnection 做爲網絡基礎架構,已經服務了成千上萬的 iOS 和 Mac OS 程序,而且作的還算至關不錯。可是這些年,一些用例——尤爲是在 iPhone 和 iPad 上面——已經對 NSURLConnection 的幾個核心概念提出了挑戰,讓蘋果有理由對它進行重構。
在 2013 的 WWDC 上,蘋果推出了 NSURLConnection 的繼任者:NSURLSession。
和 NSURLConnection 同樣,NSURLSession 指的也不只是同名類 NSURLSession,還包括一系列相互關聯的類。NSURLSession 包括了與以前相同的組件,NSURLRequest 與 NSURLCache,可是把 NSURLConnection 替換成了NSURLSession、NSURLSessionConfiguration 以及 NSURLSessionTask 的 3 個子類:NSURLSessionDataTask,NSURLSessionUploadTask,NSURLSessionDownloadTask。
與 NSURLConnection 相比,NSURLsession 最直接的改進就是能夠配置每一個 session 的緩存,協議,cookie,以及證書策略(credential policy),甚至跨程序共享這些信息。這將容許程序和網絡基礎框架之間相互獨立,不會發生干擾。每一個NSURLSession 對象都由一個 NSURLSessionConfiguration 對象來進行初始化,後者指定了剛纔提到的那些策略以及一些用來加強移動設備上性能的新選項。
NSURLSession 中另外一大塊就是 session task。它負責處理數據的加載以及文件和數據在客戶端與服務端之間的上傳和下載。NSURLSessionTask 與 NSURLConnection 最大的類似之處在於它也負責數據的加載,最大的不一樣之處在於全部的 task 共享其創造者 NSURLSession 這一公共委託者(common delegate)。
咱們先來深刻探討 task,事後再來討論 NSURLSessionConfiguration。
NSURLSessionTask
NSURLSessionTask is an abstract subclass, with three concrete subclasses that are used directly:NSURLSessionDataTask, NSURLSessionUploadTask, and NSURLSessionDownloadTask. These three classes encapsulate the three essential networking tasks of modern applications: fetching data, such as JSON or XML, and uploading and downloading files.
NSURLsessionTask 是一個抽象類,其下有 3 個實體子類能夠直接使用:NSURLSessionDataTask、NSURLSessionUploadTask、NSURLSessionDownloadTask。這 3 個子類封裝了現代程序三個最基本的網絡任務:獲取數據,好比 JSON 或者 XML,上傳文件和下載文件。
當一個 NSURLSessionDataTask 完成時,它會帶有相關聯的數據,而一個 NSURLSessionDownloadTask 任務結束時,它會帶回已下載文件的一個臨時的文件路徑。由於通常來講,服務端對於一個上傳任務的響應也會有相關數據返回,因此NSURLSessionUploadTask 繼承自 NSURLSessionDataTask。
全部的 task 都是能夠取消,暫停或者恢復的。當一個 download task 取消時,能夠經過選項來建立一個恢復數據(resume data),而後能夠傳遞給下一次新建立的 download task,以便繼續以前的下載。
不一樣於直接使用 alloc-init 初始化方法,task 是由一個 NSURLSession 建立的。每一個 task 的構造方法都對應有或者沒有completionHandler 這個 block 的兩個版本,例如:有這樣兩個構造方法 –dataTaskWithRequest: 和 –dataTaskWithRequest:completionHandler:。這與 NSURLConnection 的 -sendAsynchronousRequest:queue:completionHandler: 方法相似,經過指定 completionHandler 這個 block 將建立一個隱式的 delegate,來替代該 task 原來的 delegate——session。對於須要 override 原有 session task 的 delegate 的默認行爲的狀況,咱們須要使用這種不帶 completionHandler 的版本。
下面是用NSURLSession重構代碼,GET請求
NSLog(@"GET請求開始 %@",[NSThread currentThread]); NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login.php?username=%@&password=%@", self.userName.text, self.pwd.text]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]; NSLog(@"GET請求-NSURLRequest:%@ %@", request, [NSThread currentThread]); //構造Session NSURLSession *session = [NSURLSession sharedSession]; NSLog(@"GET請求-NSURLSession:%@ %@",session, [NSThread currentThread]); NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:urlStr] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error == nil) { NSLog(@"GET請求-NSURLResponse:%@ %@",response, [NSThread currentThread]); NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"GET請求-返回的字符串:%@ - %@", str, [NSThread currentThread]); [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.responseText.text = str; NSLog(@"GET請求-更新UI %@",[NSThread currentThread]); }]; } NSLog(@"GET請求結束 %@", [NSThread currentThread]); }]; NSLog(@"GET請求-NSURLSessionDataTask:%@ %@",task, [NSThread currentThread]); [task resume]; NSLog(@"GET請求-主線程其餘工做 %@", [NSThread currentThread]);
控制檯打印以下
而後是POST請求,代碼以下
NSLog(@"POST請求開始 %@",[NSThread currentThread]); NSString *urlStr = @"http://localhost/login.php"; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]]; //設置請求類型爲POST request.HTTPMethod = @"POST"; NSString *str = [NSString stringWithFormat:@"username=%@&password=%@", self.userName.text, self.pwd.text]; request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding]; NSLog(@"POST請求-NSMutableURLRequest:%@ %@", request, [NSThread currentThread]); //構造Session NSURLSession *session = [NSURLSession sharedSession]; NSLog(@"POST請求-NSURLSession:%@ %@",session, [NSThread currentThread]); NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error == nil) { NSLog(@"POST請求-NSURLResponse:%@ %@",response, [NSThread currentThread]); NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"POST請求-返回的字符串:%@ - %@", str, [NSThread currentThread]); [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.responseText.text = str; NSLog(@"POST請求-更新UI %@",[NSThread currentThread]); }]; } NSLog(@"POST請求結束 %@", [NSThread currentThread]); }]; NSLog(@"POST請求-NSURLSessionDataTask:%@ %@",task, [NSThread currentThread]); [task resume]; NSLog(@"POST請求-主線程其餘工做 %@", [NSThread currentThread]);
下面是控制檯打印
下面是swift版的代碼,GET請求
print("GET請求-開始-\(NSThread.currentThread())") let urlStr = "http://localhost/login.php?username=\(self.userName.text!)&password=\(self.pwd.text!)" let request = NSURLRequest(URL: NSURL(string: urlStr)!) print("GET請求-request:\(request)-\(NSThread.currentThread())") let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(NSURL(string: urlStr)!) { (responseData, response, error) -> Void in if error == nil { print("GET請求-response:\(response)-\(NSThread.currentThread())") let str = NSString(data: responseData!, encoding: NSUTF8StringEncoding)! print("GET請求-返回字符串:\(str)-\(NSThread.currentThread())") NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in self.responseText.text = String(str) print("GET請求-更新UI-\(NSThread.currentThread())") }) } } task.resume() print("GET請求-主線程其餘工做-\(NSThread.currentThread())")
控制檯打印以下
POST請求,代碼以下
print("POST請求-開始-\(NSThread.currentThread())") let urlStr = "http://localhost/login.php" //設置request let request = NSMutableURLRequest(URL: NSURL(string: urlStr)!) request.HTTPMethod = "POST" let str = "username=\(self.userName.text!)&password=\(self.pwd.text!)" request.HTTPBody = str.dataUsingEncoding(NSUTF8StringEncoding) print("POST請求-request:\(request)-\(NSThread.currentThread())") let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { (responseData, response, error) -> Void in if error == nil { print("POST請求-response:\(response)-\(NSThread.currentThread())") let str = NSString(data: responseData!, encoding: NSUTF8StringEncoding)! print("POST請求-返回字符串:\(str)-\(NSThread.currentThread())") NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in self.responseText.text = String(str) print("POST請求-更新UI-\(NSThread.currentThread())") }) } } task.resume() print("POST請求-主線程其餘工做-\(NSThread.currentThread())")
控制檯打印
2016/01/08
Day 48
今天學習JSON與XML解析,我對這兩種數據格式都有所瞭解,學起來仍是很簡單的
JSON的序列化和反序列化
[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
[NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
NSJSONReadingOptions
若是枚舉類型的起始數值是1,一般0就表示什麼選項也不支持,是效率最高的選項
NSXMLParser解析方法
NSXMLParser解析過程
實例化NSXMLParser,傳入從服務器接收的XML數據
定義解析器代理
解析器解析
經過解析代理方法完成XML數據的解析
NSXMLParser解析代理方法
// 1. 開始解析XML文檔
- (void)parserDidStartDocument:
// 2. 開始解析某個元素,會遍歷整個XML,識別元素節點名稱
- (void)parser:didStartElement:namespaceURI:qualifiedName:attributes:
// 3. 文本節點,獲得文本節點裏存儲的信息數據,對於大數據可能會接收屢次!爲了節約內存開銷
- (void)parser:foundCharacters:
// 4. 結束某個節點,存儲從parser:foundCharacters:方法中獲取到的信息
- (void)parser:didEndElement:namespaceURI:qualifiedName:
注意:在解析過程當中,二、三、4三個方法會不停的重複執行,直到遍歷完成爲止
// 5. 解析XML文檔結束
- (void)parserDidEndDocument:
// 6. 解析出錯
- (void)parser:parseErrorOccurred: