網絡請求 get post

1.新建一個網絡請求工具類,負責整個項目中全部的Http網絡請求 提示:同步請求會卡住線程,發送網絡請求應該使用異步請求(這意味着類方法不能有返回值) 2.工具類的實現 YYHttpTool.h文件 複製代碼 1 // 2 // YYHttpTool.h 3 //網絡請求工具類,負責整個項目中全部的Http網絡請求 4 5 #import 6 7 @interface YYHttpTool : NSObject 8 /** 9 * 發送一個GET請求 10 * 11 * @param url 請求路徑 12 * @param params 請求參數 13 * @param success 請求成功後的回調(請將請求成功後想作的事情寫到這個block中) 14 * @param failure 請求失敗後的回調(請將請求失敗後想作的事情寫到這個block中) 15 */ 16 + (void)get:(NSString *)url params:(NSDictionary *)params success:(void(^)(id responseObj))success failure:(void(^)(NSError *error))failure; 17 18 /** 19 * 發送一個POST請求 20 * 21 * @param url 請求路徑 22 * @param params 請求參數 23 * @param success 請求成功後的回調(請將請求成功後想作的事情寫到這個block中) 24 * @param failure 請求失敗後的回調(請將請求失敗後想作的事情寫到這個block中) 25 */ 26 + (void)post:(NSString *)url params:(NSDictionary *)params success:(void(^)(id responseObj))success failure:(void(^)(NSError *error))failure; 27 @end 複製代碼 YYHttpTool.m文件 複製代碼 1 // 2 // YYHttpTool.m 3 // 4 5 #import "YYHttpTool.h" 6 #import "AFNetworking.h" 7 @implementation YYHttpTool 8 +(void)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure 9 { 10 //1.得到請求管理者 11 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; 12 13 //3.發送Get請求 14 [mgr GET:url parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*responseObj) { 15 if (success) { 16 success(responseObj); 17 } 18 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 19 if (failure) { 20 failure(error); 21 } 22 }]; 23 } 24 25 +(void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure 26 { 27 //1.得到請求管理者 28 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; 29 30 //2.發送Post請求 31 [mgr POST:url parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*responseObj) { 32 if (success) { 33 success(responseObj); 34 } 35 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 36 if (failure) { 37 failure(error); 38 } 39 }]; 40 41 } 42 @end 複製代碼 3.在項目中用到AFN框架的地方使用工具類進行替換 YYHomeTableViewController.m文件 複製代碼 1 // 2 // YYHomeTableViewController.m 3 // 4 5 #import "YYHomeTableViewController.h" 6 #import "YYOneViewController.h" 7 #import "YYTitleButton.h" 8 #import "YYPopMenu.h" 9 #import "YYAccountModel.h" 10 #import "YYAccountTool.h" 11 //#import "AFNetworking.h" 12 #import "UIImageView+WebCache.h" 13 #import "YYUserModel.h" 14 #import "YYStatusModel.h" 15 #import "MJExtension.h" 16 #import "YYloadStatusesFooter.h" 17 #import "YYHttpTool.h" 18 19 @interface YYHomeTableViewController () 20 @property(nonatomic,assign)BOOL down; 21 @property(nonatomic,strong)NSMutableArray *statuses; 22 @property(nonatomic,strong)YYloadStatusesFooter *footer; 23 @property(nonatomic,strong) YYTitleButton *titleButton; 24 @end 25 26 @implementation YYHomeTableViewController 27 28 #pragma mark- 懶加載 29 -(NSMutableArray *)statuses 30 { 31 if (_statuses==nil) { 32 _statuses=[NSMutableArray array]; 33 } 34 return _statuses; 35 } 36 - (void)viewDidLoad 37 { 38 [super viewDidLoad]; 39 40 //設置導航欄內容 41 [self setupNavBar]; 42 43 //集成刷新控件 44 [self setupRefresh]; 45 46 //設置用戶的暱稱爲標題 47 //先顯示首頁標題,延遲兩秒以後變換成用戶暱稱 48 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 49 [self setupUserInfo]; 50 }); 51 } 52 53 /** 54 *設置用戶的暱稱爲標題 55 */ 56 -(void)setupUserInfo 57 { 58 // //1.得到請求管理者 59 // AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; 60 // 61 // //2.封裝請求參數 62 // NSMutableDictionary *params=[NSMutableDictionary dictionary]; 63 // params[@"access_token"] =[YYAccountTool accountModel].access_token; 64 // params[@"uid"]=[YYAccountTool accountModel].uid; 65 // 66 // //3.發送Get請求 67 // [mgr GET:@"https://api.weibo.com/2/users/show.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*userDict) { 68 // 69 // //字典轉模型 70 // YYUserModel *user=[YYUserModel objectWithKeyValues:userDict]; 71 // 72 // //設置標題 73 // [self.titleButton setTitle:user.name forState:UIControlStateNormal]; 74 // // 存儲帳號信息(須要先拿到帳號) 75 // YYAccountModel *account=[YYAccountTool accountModel]; 76 // account.name=user.name; 77 // //存儲 78 // [YYAccountTool save:account]; 79 // 80 // } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 81 // 82 // }]; 83 84 //1.封裝請求參數 85 NSMutableDictionary *params=[NSMutableDictionary dictionary]; 86 params[@"access_token"] =[YYAccountTool accountModel].access_token; 87 params[@"uid"]=[YYAccountTool accountModel].uid; 88 89 //2.發送網絡請求 90 [YYHttpTool get:@"https://api.weibo.com/2/users/show.json" params:params success:^(id responseObj) { 91 //字典轉模型 92 YYUserModel *user=[YYUserModel objectWithKeyValues:responseObj]; 93 //設置標題 94 [self.titleButton setTitle:user.name forState:UIControlStateNormal]; 95 // 存儲帳號信息(須要先拿到帳號) 96 YYAccountModel *account=[YYAccountTool accountModel]; 97 account.name=user.name; 98 //存儲 99 [YYAccountTool save:account]; 100 } failure:^(NSError *error) { 101 YYLog(@"請求失敗"); 102 }]; 103 } 104 105 //集成刷新控件 106 -(void)setupRefresh 107 { 108 // 1.添加下拉刷新控件 109 UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init]; 110 [self.tableView addSubview:refreshControl]; 111 112 //2.監聽狀態 113 [refreshControl addTarget:self action:(@selector(refreshControlStateChange:)) forControlEvents:UIControlEventValueChanged]; 114 115 //3.讓刷新控件自動進入到刷新狀態 116 [refreshControl beginRefreshing]; 117 118 //4.手動調用方法,加載數據 119 //模擬網絡延遲,延遲2.0秒 120 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 121 [self refreshControlStateChange:refreshControl]; 122 }); 123 124 //5.上拉刷新數據 125 YYloadStatusesFooter *footer=[YYloadStatusesFooter loadFooter]; 126 self.tableView.tableFooterView=footer; 127 self.footer=footer; 128 } 129 130 /** 131 * 當下拉刷新控件進入刷新狀態(轉圈圈)的時候會自動調用 132 */ 133 -(void)refreshControlStateChange:(UIRefreshControl *)refreshControl 134 { 135 //1.封裝請求參數 136 NSMutableDictionary *params=[NSMutableDictionary dictionary]; 137 params[@"access_token"] =[YYAccountTool accountModel].access_token; 138 //取出當前微博模型中的第一條數據,獲取第一條數據的id 139 YYStatusModel *firstStatus=[self.statuses firstObject]; 140 if (firstStatus) { 141 params[@"since_id"]=firstStatus.idstr; 142 } 143 144 //2.發送網絡請求 145 [YYHttpTool get:@"https://api.weibo.com/2/statuses/home_timeline.json" params:params success:^(id responseObj) { 146 147 // 微博字典 -- 數組 148 NSArray *statusDictArray = responseObj[@"statuses"]; 149 //微博字典數組---》微博模型數組 150 NSArray *newStatuses =[YYStatusModel objectArrayWithKeyValuesArray:statusDictArray]; 151 152 //把新數據添加到舊數據的前面 153 NSRange range=NSMakeRange(0, newStatuses.count); 154 NSIndexSet *indexSet=[NSIndexSet indexSetWithIndexesInRange:range]; 155 [self.statuses insertObjects:newStatuses atIndexes:indexSet]; 156 YYLog(@"刷新了--%d條新數據",newStatuses.count); 157 158 //從新刷新表格 159 [self.tableView reloadData]; 160 //讓刷新控件中止刷新(回覆默認的狀態) 161 [refreshControl endRefreshing]; 162 [self showNewStatusesCount:newStatuses.count]; 163 164 } failure:^(NSError *error) { 165 166 YYLog(@"請求失敗"); 167 //讓刷新控件中止刷新(回覆默認的狀態) 168 [refreshControl endRefreshing]; 169 }]; 170 } 171 172 /** 173 * 加載更多的微博數據 174 */ 175 - (void)loadMoreStatuses 176 { 177 // 1.封裝請求參數 178 NSMutableDictionary *params = [NSMutableDictionary dictionary]; 179 params[@"access_token"] = [YYAccountTool accountModel].access_token; 180 YYStatusModel *lastStatus = [self.statuses lastObject]; 181 if (lastStatus) { 182 params[@"max_id"] = @([lastStatus.idstr longLongValue] - 1); 183 } 184 185 //2.發送網絡請求 186 [YYHttpTool get:@"https://api.weibo.com/2/statuses/home_timeline.json" params:params success:^(id responseObj) { 187 // 微博字典數組 188 NSArray *statusDictArray = responseObj[@"statuses"]; 189 // 微博字典數組 ---> 微博模型數組 190 NSArray *newStatuses = [YYStatusModel objectArrayWithKeyValuesArray:statusDictArray]; 191 192 // 將新數據插入到舊數據的最後面 193 [self.statuses addObjectsFromArray:newStatuses]; 194 195 // 從新刷新表格 196 [self.tableView reloadData]; 197 198 // 讓刷新控件中止刷新(恢復默認的狀態) 199 [self.footer endRefreshing]; 200 201 } failure:^(NSError *error) { 202 YYLog(@"請求失敗--%@", error); 203 // 讓刷新控件中止刷新(恢復默認的狀態) 204 [self.footer endRefreshing]; 205 }]; 206 } 207 208 /** 209 * 提示用戶最新的微博數量 210 * 211 * @param count 最新的微博數量 212 */ 213 -(void)showNewStatusesCount:(int)count 214 { 215 //1.建立一個label 216 UILabel *label=[[UILabel alloc]init]; 217 218 //2.設置label的文字 219 if (count) { 220 label.text=[NSString stringWithFormat:@"共有%d條新的微博數據",count]; 221 }else 222 { 223 label.text=@"沒有最新的微博數據"; 224 } 225 226 //3.設置label的背景和對其等屬性 227 label.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageWithName:@"timeline_new_status_background"]]; 228 label.textAlignment=UITextAlignmentCenter; 229 label.textColor=[UIColor whiteColor]; 230 231 //4.設置label的frame 232 label.x=0; 233 label.width=self.view.width; 234 label.height=35; 235 // label.y=64-label.height; 236 label.y=self.navigationController.navigationBar.height+20-label.height; 237 238 //5.把lable添加到導航控制器的View上 239 // [self.navigationController.view addSubview:label]; 240 //把label添加到導航控制器上,顯示在導航欄的下面 241 [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar]; 242 243 //6.設置動畫效果 244 CGFloat duration=0.75; 245 //設置提示條的透明度 246 label.alpha=0.0; 247 [UIView animateWithDuration:duration animations:^{ 248 //往下移動一個label的高度 249 label.transform=CGAffineTransformMakeTranslation(0, label.height); 250 label.alpha=1.0; 251 } completion:^(BOOL finished) {//向下移動完畢 252 253 //延遲delay秒的時間後,在執行動畫 254 CGFloat delay=0.5; 255 256 [UIView animateKeyframesWithDuration:duration delay:delay options:UIViewAnimationOptionCurveEaseOut animations:^{ 257 258 //恢復到原來的位置 259 label.transform=CGAffineTransformIdentity; 260 label.alpha=0.0; 261 262 } completion:^(BOOL finished) { 263 264 //刪除控件 265 [label removeFromSuperview]; 266 }]; 267 }]; 268 } 269 270 /** 271 UIViewAnimationOptionCurveEaseInOut = 0 << 16, // 開始:由慢到快,結束:由快到慢 272 UIViewAnimationOptionCurveEaseIn = 1 << 16, // 由慢到塊 273 UIViewAnimationOptionCurveEaseOut = 2 << 16, // 由快到慢 274 UIViewAnimationOptionCurveLinear = 3 << 16, // 線性,勻速 275 */ 276 277 /**設置導航欄內容*/ 278 -(void)setupNavBar 279 { 280 self.navigationItem.leftBarButtonItem=[UIBarButtonItem itemWithImageName:@"navigationbar_friendsearch" highImageName:@"navigationbar_friendsearch_highlighted" target:self action:@selector(friendsearch)]; 281 self.navigationItem.rightBarButtonItem=[UIBarButtonItem itemWithImageName:@"navigationbar_pop" highImageName:@"navigationbar_pop_highlighted" target:self action:@selector(pop)]; 282 283 //設置導航欄按鈕 284 YYTitleButton *titleButton=[[YYTitleButton alloc]init]; 285 286 //設置尺寸 287 // titleButton.width=100; 288 titleButton.height=35; 289 290 //設置文字 291 YYAccountModel *account= [YYAccountTool accountModel]; 292 NSString *name=account.name; 293 NSLog(@"%@",name); 294 // name=@"yangye"; 295 //判斷:若是name有值(上一次登陸的用戶名),那麼就使用上次的,若是沒有那麼就設置爲首頁 296 if (name) { 297 [titleButton setTitle:name forState:UIControlStateNormal]; 298 }else{ 299 [titleButton setTitle:@"首頁" forState:UIControlStateNormal]; 300 } 301 //設置圖標 302 [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal]; 303 //設置背景 304 [titleButton setBackgroundImage:[UIImage resizedImage:@"navigationbar_filter_background_highlighted"] forState:UIControlStateHighlighted]; 305 306 //設置尺寸 307 // titleButton.width=100; 308 // titleButton.height=35; 309 //監聽按鈕的點擊事件 310 [titleButton addTarget:self action:@selector(titleButtonClick:) forControlEvents:UIControlEventTouchUpInside]; 311 self.navigationItem.titleView=titleButton; 312 self.titleButton=titleButton; 313 } 314 -(void)titleButtonClick:(UIButton *)titleButton 315 { 316 317 [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_up"] forState:UIControlStateNormal]; 318 319 UITableView *tableView=[[UITableView alloc]init]; 320 [tableView setBackgroundColor:[UIColor yellowColor]]; 321 YYPopMenu *menu=[YYPopMenu popMenuWithContentView:tableView]; 322 [menu showInRect:CGRectMake(60, 55, 200, 200)]; 323 menu.dimBackground=YES; 324 325 menu.arrowPosition=YYPopMenuArrowPositionRight; 326 menu.delegate=self; 327 } 328 329 330 #pragma mark-YYPopMenuDelegate 331 //彈出菜單 332 -(void)popMenuDidDismissed:(YYPopMenu *)popMenu 333 { 334 YYTitleButton *titleButton=(YYTitleButton *)self.navigationItem.titleView; 335 [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal]; 336 } 337 -(void)pop 338 { 339 YYLog(@"---POP---"); 340 } 341 -(void)friendsearch 342 { 343 //跳轉到one這個子控制器界面 344 YYOneViewController *one=[[YYOneViewController alloc]init]; 345 one.title=@"One"; 346 //拿到當前控制器 347 [self.navigationController pushViewController:one animated:YES]; 348 349 } 350 351 #pragma mark - Table view data source 352 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 353 { 354 #warning 監聽tableView每次顯示數據的過程 355 //在tableView顯示以前,判斷有沒有數據,若有有數據那麼就顯示底部視圖 356 self.footer.hidden=self.statuses.count==0; 357 return self.statuses.count; 358 } 359 360 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 361 { 362 static NSString *ID = @"cell"; 363 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; 364 if (!cell) { 365 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID]; 366 } 367 368 //取出這行對應的微博字典數據,轉換爲數據模型 369 YYStatusModel *status=self.statuses[indexPath.row]; 370 cell.textLabel.text=status.text; 371 cell.detailTextLabel.text=status.user.name; 372 NSString *imageUrlStr=status.user.profile_image_url; 373 [cell.imageView setImageWithURL:[NSURL URLWithString:imageUrlStr] placeholderImage:[UIImage imageWithName:@"avatar_default_small"]]; 374 375 return cell; 376 } 377 378 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 379 { 380 //點擊cell的時候,跳到下一個界面 381 UIViewController *newVc = [[UIViewController alloc] init]; 382 newVc.view.backgroundColor = [UIColor redColor]; 383 newVc.title = @"新控制器"; 384 [self.navigationController pushViewController:newVc animated:YES]; 385 } 386 387 #pragma mark-代理方法 388 - (void)scrollViewDidScroll:(UIScrollView *)scrollView 389 { 390 if (self.statuses.count <= 0 || self.footer.isRefreshing) return; 391 392 // 1.差距 393 CGFloat delta = scrollView.contentSize.height - scrollView.contentOffset.y; 394 // 恰好能完整看到footer的高度 395 CGFloat sawFooterH = self.view.height - self.tabBarController.tabBar.height; 396 397 // 2.若是能看見整個footer 398 if (delta <= (sawFooterH - 0)) { 399 // 進入上拉刷新狀態 400 [self.footer beginRefreshing]; 401 402 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 403 // 加載更多的微博數據 404 [self loadMoreStatuses]; 405 }); 406 } 407 } 408 @end 複製代碼 受權控制器 YYOAuthViewController.m文件 複製代碼 1 // 2 // YYOAuthViewController.m 3 // 4 5 #import "YYOAuthViewController.h" 6 #import "MBProgressHUD+MJ.h" 7 //#import "AFNetworking.h" 8 #import "YYTabBarViewController.h" 9 #import "YYNewfeatureViewController.h" 10 #import "YYControllerTool.h" 11 #import "YYAccountModel.h" 12 #import "YYAccountTool.h" 13 #import "YYHttpTool.h" 14 15 @interface YYOAuthViewController () 16 17 @end 18 19 @implementation YYOAuthViewController 20 21 - (void)viewDidLoad 22 { 23 [super viewDidLoad]; 24 25 //1.建立UIWebView 26 UIWebView *webView=[[UIWebView alloc]init]; 27 webView.frame=self.view.bounds; 28 [self.view addSubview:webView]; 29 30 31 //2.加載登錄界面 32 NSString *urlStr=[NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",YYAppKey,YYRedirectURI]; 33 NSURL *url=[NSURL URLWithString:urlStr]; 34 NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url]; 35 [webView loadRequest:request]; 36 37 //3.設置代理 38 webView.delegate=self; 39 } 40 41 #pragma mark-UIWebViewDelegate 42 /** 43 * UIWebView開始加載資源的時候調用(開始發送請求) 44 */ 45 -(void)webViewDidStartLoad:(UIWebView *)webView 46 { 47 [MBProgressHUD showMessage:@"正在努力加載中···"]; 48 } 49 50 /** 51 * UIWebView加載完畢的時候調用(請求結束) 52 */ 53 -(void)webViewDidFinishLoad:(UIWebView *)webView 54 { 55 [MBProgressHUD hideHUD]; 56 } 57 58 /** 59 * UIWebView加載失敗的時候調用(請求失敗) 60 */ 61 -(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error 62 { 63 [MBProgressHUD hideHUD]; 64 } 65 66 /** 67 * UIWebView每當發送一個請求以前,都會先調用這個代理方法(詢問代理允不容許加載這個請求) 68 * @param request 即將發送的請求 69 * @return YES容許加載,NO不容許加載 70 */ 71 -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 72 { 73 //1.得到請求地址 74 NSString *urlStr=request.URL.absoluteString; 75 // NSLog(@"%@",urlStr); 76 77 //2.判斷url是否爲回調地址 78 //urlStr在字符串中的範圍 79 //設置從等號位置開始,不用再額外的找位置 80 NSString *redirectURI=[NSString stringWithFormat:@"%@?code=",YYRedirectURI]; 81 NSRange range=[urlStr rangeOfString:redirectURI]; 82 //判斷是否爲回調地址 83 if (range.location!=NSNotFound) {//是回調地址 84 //截取受權成功後的請求標記 85 int from=range.location+range.length; 86 NSString *code=[urlStr substringFromIndex:from]; 87 // YYLog(@"%@--%@--",urlStr,code); 88 89 //根據code得到一個accessToken 90 [self accessTokenWithCode:code]; 91 92 //禁止加載回調頁面,拿到想要的東西就行了。 93 return NO; 94 } 95 return YES; 96 } 97 /** 98 * 根據code得到一個accessToken(發送一個Post請求) 99 * @param code 受權成功後的請求標記 100 */ 101 -(void)accessTokenWithCode:(NSString *)code 102 { 103 //1.封裝請求參數 104 NSMutableDictionary *params=[NSMutableDictionary dictionary]; 105 params[@"client_id"] =YYAppKey; 106 params[@"client_secret"] =YYAppSecret; 107 params[@"grant_type"] =@"authorization_code"; 108 params[@"code"] =code; 109 params[@"redirect_uri"] =YYRedirectURI; 110 111 //2.發送網絡請求 112 [YYHttpTool post:@"https://api.weibo.com/oauth2/access_token" params:params success:^(id responseObj) { 113 //隱藏遮罩 114 [MBProgressHUD hideHUD]; 115 116 //字典轉模型 117 YYAccountModel *accountmodel=[YYAccountModel accountModelWithDcit:responseObj]; 118 //存儲帳號模型 119 [YYAccountTool save:accountmodel]; 120 121 //3.2切換控制器 122 [YYControllerTool chooseRootViewController]; 123 124 YYLog(@"請求成功"); 125 126 } failure:^(NSError *error) { 127 //隱藏遮罩 128 [MBProgressHUD hideHUD]; 129 YYLog(@"請求失敗"); 130 }]; 131 } 132 @end 複製代碼 發微博控制器中的處理(說明:發送帶圖片的微博暫時未作處理) YYComposeViewController.m文件 複製代碼 1 // 2 // YYComposeViewController.m 3 // 4 5 #import "YYComposeViewController.h" 6 #import "YYTextView.h" 7 #import "YYComposeToolBar.h" 8 #import "YYComposePhotosView.h" 9 #import "YYAccountModel.h" 10 #import "YYAccountTool.h" 11 //#import "AFNetworking.h" 12 #import "MBProgressHUD+MJ.h" 13 #import "YYHttpTool.h" 14 15 @interface YYComposeViewController () 16 @property(nonatomic,weak)YYTextView *textView; 17 @property(nonatomic,weak)YYComposeToolBar *toolBar; 18 @property(nonatomic,weak)YYComposePhotosView *photoView; 19 @end 20 21 @implementation YYComposeViewController 22 23 #pragma mark-初始化方法 24 - (void)viewDidLoad 25 { 26 [super viewDidLoad]; 27 28 //設置導航欄 29 [self setupNavBar]; 30 31 //添加子控件 32 [self setupTextView]; 33 34 //添加工具條 35 [self setupToolbar]; 36 37 //添加photoView 38 [self setupPhotoView]; 39 40 //寫圖片代碼,把五張圖片寫入到相冊中保存 41 for (int i=0; i<5; i++) { 42 NSString *name=[NSString stringWithFormat:@"minion_0%d",i+1]; 43 UIImage *image=[UIImage imageNamed:name]; 44 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); 45 } 46 47 } 48 49 -(void)setupPhotoView 50 { 51 YYComposePhotosView *photoView=[[YYComposePhotosView alloc]init]; 52 photoView.width=self.textView.width; 53 photoView.height=self.textView.height; 54 photoView.y=50; 55 // photoView.backgroundColor=[UIColor redColor]; 56 [self.textView addSubview:photoView]; 57 self.photoView=photoView; 58 } 59 -(void)setupToolbar 60 { 61 //1.建立 62 YYComposeToolBar *toolBar=[[YYComposeToolBar alloc]init]; 63 toolBar.width=self.view.width; 64 toolBar.height=44; 65 self.toolBar=toolBar; 66 //設置代理 67 toolBar.delegate=self; 68 69 //2.顯示 70 // self.textView.inputAccessoryView=toolBar; 71 toolBar.y=self.view.height-toolBar.height; 72 [self.view addSubview:toolBar]; 73 } 74 75 76 /** 77 * view顯示完畢的時候再彈出鍵盤,避免顯示控制器view的時候會卡住 78 */ 79 - (void)viewDidAppear:(BOOL)animated 80 { 81 [super viewDidAppear:animated]; 82 83 // 成爲第一響應者(叫出鍵盤) 84 [self.textView becomeFirstResponder]; 85 } 86 87 #pragma mark-UITextViewDelegate 88 /** 89 * 當用戶開始拖拽scrollView時調用 90 */ 91 -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView 92 { 93 [self.view endEditing:YES]; 94 } 95 96 //添加子控件 97 -(void)setupTextView 98 { 99 //1.建立輸入控件 100 YYTextView *textView=[[YYTextView alloc]init]; 101 //設置垂直方向上擁有彈簧效果 102 textView.alwaysBounceVertical=YES; 103 textView.delegate=self; 104 //設置frame 105 textView.frame=self.view.bounds; 106 [self.view addSubview:textView]; 107 self.textView=textView; 108 109 //2.設置佔位文字提醒 110 textView.placehoder=@"分享新鮮事···"; 111 //3.設置字體(說明:該控件繼承自UITextfeild,font是其父類繼承下來的屬性) 112 textView.font=[UIFont systemFontOfSize:15]; 113 //設置佔位文字的顏色爲棕色 114 textView.placehoderColor=[UIColor lightGrayColor]; 115 116 //4.監聽鍵盤 117 //鍵盤的frame(位置即將改變),就會發出UIKeyboardWillChangeFrameNotification通知 118 //鍵盤即將彈出,就會發出UIKeyboardWillShowNotification通知 119 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(KeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; 120 //鍵盤即將隱藏,就會發出UIKeyboardWillHideNotification通知 121 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(KeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; 122 } 123 124 -(void)dealloc 125 { 126 [[NSNotificationCenter defaultCenter]removeObserver:self]; 127 } 128 129 #pragma mark-設置代理方法 130 /** 131 *當textView的內容改變的時候,通知導航欄「發送」按鈕爲可用 132 */ 133 -(void)textViewDidChange:(UITextView *)textView 134 { 135 self.navigationItem.rightBarButtonItem.enabled=textView.text.length!=0; 136 } 137 #pragma mark-鍵盤處理 138 /** 139 *鍵盤即將彈出 140 */ 141 -(void)KeyboardWillShow:(NSNotification *)note 142 { 143 YYLog(@"%@",note.userInfo); 144 //1.鍵盤彈出須要的時間 145 CGFloat duration=[note.userInfo [UIKeyboardAnimationDurationUserInfoKey] doubleValue]; 146 147 //2.動畫 148 [UIView animateWithDuration:duration animations:^{ 149 //取出鍵盤的高度 150 CGRect keyboardF=[note.userInfo [UIKeyboardFrameEndUserInfoKey] CGRectValue]; 151 CGFloat keyboardH=keyboardF.size.height; 152 self.toolBar.transform=CGAffineTransformMakeTranslation(0, -keyboardH); 153 }]; 154 } 155 156 /** 157 *鍵盤即將隱藏 158 */ 159 -(void)KeyboardWillHide:(NSNotification *)note 160 { 161 //1.鍵盤彈出須要的時間 162 CGFloat duration=[note.userInfo [UIKeyboardAnimationDurationUserInfoKey] doubleValue]; 163 //2.動畫 164 [UIView animateWithDuration:duration animations:^{ 165 self.toolBar.transform=CGAffineTransformIdentity; 166 }]; 167 } 168 169 //設置導航欄 170 -(void)setupNavBar 171 { 172 self.title=@"發消息"; 173 self.view.backgroundColor=[UIColor whiteColor]; 174 self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(cancel)]; 175 self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"發送" style:UIBarButtonItemStyleBordered target:self action:@selector(send)]; 176 self.navigationItem.rightBarButtonItem.enabled=NO; 177 } 178 179 -(void)send 180 { 181 //1.發表微博 182 if (self.photoView.images.count) { 183 [self sendStatusWithImage]; 184 }else 185 { 186 [self sendStatusWithoutImage]; 187 } 188 //2.退出控制器 189 [self dismissViewControllerAnimated:YES completion:nil]; 190 } 191 192 /** 193 * 發送帶圖片的微博 194 */ 195 -(void)sendStatusWithImage 196 { 197 // //1.得到請求管理者 198 // AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; 199 // 200 // //2.封裝請求參數 201 // NSMutableDictionary *params=[NSMutableDictionary dictionary]; 202 // params[@"access_token"] =[YYAccountTool accountModel].access_token; 203 // params[@"status"]=self.textView.text; 204 // 205 // //3.發送POST請求 206 //// [mgr POST:@"https://api.weibo.com/2/statuses/update.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*statusDict) { 207 //// 208 //// } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 209 //// 210 //// }]; 211 // [mgr POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:params constructingBodyWithBlock:^(id formData) { 212 //#warning 目前新浪提供的發微博接口只能上傳一張圖片 213 // //取出圖片 214 // UIImage *image=[self.photoView.images firstObject]; 215 // //把圖片寫成NSData 216 // NSData *data=UIImageJPEGRepresentation(image, 1.0); 217 // //拼接文件參數 218 // [formData appendPartWithFileData:data name:@"pic" fileName:@"status.jpg" mimeType:@"image/jpeg"]; 219 // 220 // } success:^(AFHTTPRequestOperation *operation, id responseObject) { 221 // [MBProgressHUD showSuccess:@"發表成功"]; 222 // } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 223 // [MBProgressHUD showError:@"發表失敗"]; 224 // }]; 225 } 226 227 /** 228 * 發送不帶圖片的微博 229 */ 230 -(void)sendStatusWithoutImage 231 { 232 // 233 // //1.得到請求管理者 234 // AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; 235 // 236 // //2.封裝請求參數 237 // NSMutableDictionary *params=[NSMutableDictionary dictionary]; 238 // params[@"access_token"] =[YYAccountTool accountModel].access_token; 239 // params[@"status"]=self.textView.text; 240 // 241 // //3.發送POST請求 242 // [mgr POST:@"https://api.weibo.com/2/statuses/update.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*statusDict) { 243 // [MBProgressHUD showSuccess:@"發表成功"]; 244 // } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 245 // [MBProgressHUD showError:@"發表失敗"]; 246 // }]; 247 // 248 // //4.關閉發送微博界面 249 //// [self dismissViewControllerAnimated:YES completion:nil]; 250 251 //1.封裝請求參數 252 NSMutableDictionary *params=[NSMutableDictionary dictionary]; 253 params[@"access_token"] =[YYAccountTool accountModel].access_token; 254 params[@"status"]=self.textView.text; 255 256 //2.發送網絡請求 257 [YYHttpTool post:@"https://api.weibo.com/2/statuses/update.json" params:params success:^(id responseObj) { 258 [MBProgressHUD showSuccess:@"發表成功"]; 259 } failure:^(NSError *error) { 260 [MBProgressHUD showError:@"發表失敗"]; 261 }]; 262 } 263 -(void)cancel 264 { 265 [self dismissViewControllerAnimated:YES completion:nil]; 266 // self.textView.text=@"測試"; 267 } 268 269 270 #pragma mark-YYComposeToolBarDelegate 271 -(void)composeTool:(YYComposeToolBar *)toolbar didClickedButton:(YYComposeToolbarButtonType)buttonType 272 { 273 switch (buttonType) { 274 case YYComposeToolbarButtonTypeCamera://照相機 275 [self openCamera]; 276 break; 277 278 case YYComposeToolbarButtonTypePicture://相冊 279 [self openAlbum]; 280 break; 281 282 case YYComposeToolbarButtonTypeEmotion://表情 283 [self openEmotion]; 284 break; 285 286 case YYComposeToolbarButtonTypeMention://提到 287 YYLog(@"提到"); 288 break; 289 290 case YYComposeToolbarButtonTypeTrend://話題 291 YYLog(@"打開話題"); 292 break; 293 294 default: 295 break; 296 } 297 } 298 299 /** 300 * 打開照相機 301 */ 302 -(void)openCamera 303 { 304 //若是不能用,則直接返回 305 if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return; 306 307 UIImagePickerController *ipc=[[UIImagePickerController alloc]init]; 308 ipc.sourceType=UIImagePickerControllerSourceTypeCamera; 309 ipc.delegate=self; 310 [self presentViewController:ipc animated:YES completion:nil]; 311 312 } 313 /** 314 * 打開相冊 315 */ 316 -(void)openAlbum 317 { 318 //若是不能用,則直接返回 319 if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return; 320 321 UIImagePickerController *ipc=[[UIImagePickerController alloc]init]; 322 ipc.sourceType=UIImagePickerControllerSourceTypePhotoLibrary; 323 ipc.delegate=self; 324 [self presentViewController:ipc animated:YES completion:nil]; 325 } 326 /** 327 * 打開表情 328 */ 329 -(void)openEmotion 330 { 331 332 } 333 334 #pragma mark-UIImagePickerControllerDelegate 335 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 336 { 337 [picker dismissViewControllerAnimated:YES completion:nil]; 338 //1.取出選取的圖片 339 UIImage *image=info[UIImagePickerControllerOriginalImage]; 340 341 //2.添加圖片到相冊中 342 [self.photoView addImage:image]; 343 } 344 @end
相關文章
相關標籤/搜索