一:安裝Podsjavascript
0.cd到項目目錄html
1.建立podfile文件java
pod initnginx
3.在podfile文件中輸入json
pod 'AFNetworking'app
4.安裝AFNetworking,帶參數表示只安裝框架 pod自己並不更新框架
pod install --no-repo-update異步
--no-repo-update Skip running `pod repo update` before install工具
5.安裝以後使用wordspace打開url
進行簡單封裝
二: NetworkTools的工具類的封裝
#import "NetworkTools.h" @implementation NetworkTools // 單例 + (instancetype)sharedTools { static NetworkTools *tools; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ // 注意:該url末尾必定要有 '/' 這個在官方文檔已經寫了 NSURL *baseURL = [NSURL URLWithString:@"http://www.weather.com.cn/"]; tools = [[self alloc] initWithBaseURL:baseURL]; // 設置反序列化格式 此步驟若是沒有回報一個經典錯誤在下面 tools.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil]; }); return tools; } // 封裝 , block做爲參數傳遞 - (void)request:(NSString *)URLString parameters:(id)parameters finished:(void(^)(id result, NSError *error))finished { // 調用GET方法 [self GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { // 異步執行的時候, 執行完後成功的回調 // 這裏是把block做爲參數傳遞進來了, 在這裏執行ViewController中準備好的代碼 finished(responseObject, nil); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"%@", error); finished(nil, error); }]; } @end
經典錯誤: status code: 200,,可是failed: unacceptable content-type: text/html,因此要在反序列化的時候加入一個這個類型
UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7ffa9d113e60> { URL: http://www.weather.com.cn/adat/sk/101010100.html } { status code: 200, headers {
Age = 159;
Connection = "keep-alive";
"Content-Type" = "text/html";
Date = "Fri, 05 Feb 2016 06:35:48 GMT";
Server = nginx;
"Transfer-Encoding" = Identity;
"X-Via" = "1.1 bianwangtong38:5 (Cdn Cache Server V2.0)";
} }, NSErrorFailingURLKey=http://www.weather.com.cn/adat/sk/101010100.html, com.alamofire.serialization.response.error.data=<7b227765 61746865 72696e66 6f223a7b 22636974 79223a22 e58c97e4 baac222c 22636974 79696422 3a223130 31303130 31303022 2c227465 6d70223a 22313022 2c225744 223a22e4 b89ce58d 97e9a38e 222c2257 53223a22 32e7baa7 222c2253 44223a22 32362522 2c225753 45223a22 32222c22 74696d65 223a2231 303a3235 222c2269 73526164 6172223a 2231222c 22526164 6172223a 224a435f 52414441 525f415a 39303130 5f4a4222 2c226e6a 64223a22 e69a82e6 97a0e5ae 9ee586b5 222c2271 79223a22 31303132 227d7d>, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}