身為一名學生、一名 iOS 開發學習者,我瀏覽資訊(包括部落格)時,多半是在行動裝置上。然而當時 CSDN 並沒有現成的用戶端(只有 web 版)。
我曾看過一款開源的導出工具,但它是基於 Windows 平台的,只能導出 PDF,而且需要精確的 URL,無法做到「邊瀏覽邊導出」。
我真正想要的是:能在沒有網路的情況下瀏覽自己收藏的文章,並對收藏內容做分類管理;更重要的是,能為自己的文章做一份備份。我曾遇過 CSDN 帳號密碼外洩、他人登入張貼垃圾文章,導致部落格被封一天——那時我已寫了 170 篇學習筆記,卻沒有備份,可以想見當時有多慌。可見備份自己文章的重要性。
基於這些原因,這款 iOS 平台的部落格導出工具便應運而生。
註:本文參與 2014 年 CSDN 部落格大賽,投票連結:https://vote.blog.csdn.net/Article/Details?articleid=31768677
支援線上瀏覽 CSDN 部落格;可導出類型包括單篇文章、專欄、指定作者的全部文章;導出方式可為「當前瀏覽的博文/專欄」或「指定 URL」;並支援分類管理、關鍵字查詢、自動排版與圖片自適應縮放。
運行效果:

原始碼:https://github.com/colin1994/csdnBlog.git
需要具備的知識:Objective-C 基礎、StoryBoard、UITextField/UITextView、UIWebView、iOS 與 JavaScript 的互動,以及遞迴目錄遍歷、NSKeyedArchiver 檔案存儲與讀取等。
在 AppDelegate 中宣告屬性:
@property (strong, nonatomic) UIImageView *splashView;
加入啟動動畫,依螢幕高度選擇不同的背景圖:
[self.window makeKeyAndVisible];
splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, Screen_height)];
if ([[UIScreen mainScreen] bounds].size.height == 568) {
[splashView setImage:[UIImage imageNamed:@"bgBlog-568"]];
} else {
[splashView setImage:[UIImage imageNamed:@"bgBlog"]];
}
[self.window addSubview:splashView];
[self.window bringSubviewToFront:splashView];
[self performSelector:@selector(scale) withObject:nil afterDelay:0.0f];
[self performSelector:@selector(showWord) withObject:nil afterDelay:2.5f];動畫具體實作——先讓 logo 放大,再讓文字淡入:
-(void)scale {
UIImageView *logo_ = [[UIImageView alloc] initWithFrame:CGRectMake(119, 88, 82, 82)];
logo_.image = [UIImage imageNamed:@"csdnLogo"];
[splashView addSubview:logo_];
[self setAnimation:logo_];
}
-(void)setAnimation:(UIImageView *)nowView {
[UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^{
[nowView setFrame:CGRectMake(nowView.frame.origin.x - nowView.frame.size.width * 0.1,
nowView.frame.origin.y - nowView.frame.size.height * 0.1,
nowView.frame.size.width * 1.2,
nowView.frame.size.height * 1.2)];
} completion:^(BOOL finished) {
[nowView removeFromSuperview];
}];
}
-(void)showWord {
UIImageView *word_ = [[UIImageView alloc] initWithFrame:CGRectMake(75, Screen_height - 100, 170, 29)];
word_.image = [UIImage imageNamed:@"word_"];
[splashView addSubview:word_];
word_.alpha = 0.0;
[UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^{
word_.alpha = 1.0;
} completion:^(BOOL finished) {
[NSThread sleepForTimeInterval:1.0f];
[splashView removeFromSuperview];
}];
}導入蘋果官方的 Reachability.h/.m 來判斷網路狀態。之所以要判斷 Wi-Fi,是因為導出文章可能消耗較多流量,需要提示使用者開啟 Wi-Fi 再下載。
#import "Reachability.h" // Wi-Fi
if ([Reachability reachabilityForInternetConnection].currentReachabilityStatus == ReachableViaWiFi) {
// 執行你的下載邏輯
}UIWebView 有個 stringByEvaluatingJavaScriptFromString 方法,可把 JavaScript 嵌進頁面,藉此與網頁元素互動。常見用法包括:
// 1. 獲取當前頁面 URL
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
}
// 2. 獲取頁面標題
NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
// 3. 修改介面元素的值
NSString *js_result = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('q')[0].value='Colin';"];
// 4. 表單提交
NSString *js_result2 = [webView stringByEvaluatingJavaScriptFromString:@"document.forms[0].submit();"];以導出單篇為例,我們要抓取博文正文與標題。打開博文檢視原始碼,可看到 id 為 article_content 的元素對應正文:
// 獲取詳細內容 NSString *lJs = @"document.getElementById(\"article_content\").innerHTML"; NSString *lHtml1 = [webView stringByEvaluatingJavaScriptFromString:lJs];
文章標題同理:
// 獲取標題 NSString *lJs2 = @"document.getElementById(\"article_details\").getElementsByClassName(\"article_title\")[0].getElementsByTagName(\"a\")[0].innerText"; NSString *lHtml2 = [webView stringByEvaluatingJavaScriptFromString:lJs2];
再深入一點,甚至能修改網頁中圖片的大小,讓導出的內容排版更整齊:
// 修改圖片大小 if ([lHtml1 rangeOfString:@"(四)自訂 HUD 加載效果
系統自帶的轉圈菊花實在不好看。這裡導入 SVProgressHUD,顯示一個不封閉的圈並把背景壓暗,突出加載過程。
#import "SVProgressHUD.h" // 顯示 HUD [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeGradient]; // 移除 HUD [SVProgressHUD dismiss];加載效果:
(五)UITableView 列表基本操作
這裡著重介紹左滑刪除。刪除時要同時做到:從列表移除、從資料移除、刷新列表。
// 開啟刪除模式 -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { return UITableViewCellEditingStyleDelete; } // 改變刪除按鈕標題 -(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath { return @"刪除"; } // 執行刪除 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *namePath = [documentsDirectory stringByAppendingPathComponent:@"csdnInfo.plist"]; [blogArr removeObjectAtIndex:indexPath.row]; [blogArr writeToFile:namePath atomically:YES]; [nameList removeObjectAtIndex:indexPath.row]; [myTableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; } }(六)列表關鍵字模糊查詢
普通的關鍵字搜尋大家應該都會,這裡要實現的是「模糊查詢」——例如搜「iOS開發」,輸入 i、o 開 等片段都能命中。導入 DDList 相關檔案後,初始化提示列表並監聽輸入變化:
#import "DDList.h" #import "PassValueDelegate.h" // 提示列表初始化 nameList = [[NSMutableArray alloc] init]; for (int i = 0; i < [blogArr count]; i++) { [nameList addObject:[[blogArr objectAtIndex:i] objectForKey:@"name"]]; } _searchStr = @""; _ddList = [[DDList alloc] initWithStyle:UITableViewStylePlain]; _ddList._delegate = self; [self.view addSubview:_ddList.view]; [_ddList.view setFrame:CGRectMake(30, 108, 200, 0)]; _ddList._totalList = nameList;當搜尋框文字變化時更新提示列表,選中某項後自動跳轉並高亮對應列:
// 隱藏/顯示提示視圖 - (void)setDDListHidden:(BOOL)hidden { NSInteger height = hidden ? 0 : 180; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:.2]; [_ddList.view setFrame:CGRectMake(30, 108, 200, height)]; [UIView commitAnimations]; } // 搜索框文字變化時呼叫 - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { if ([searchText length] != 0) { _ddList._searchText = searchText; [_ddList updateData]; [self setDDListHidden:NO]; } else { [self setDDListHidden:YES]; } } // 點擊搜尋 - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { [self setDDListHidden:YES]; _searchStr = [searchBar text]; [searchBar resignFirstResponder]; for (int i = 0; i < [blogArr count]; i++) { if ([[[blogArr objectAtIndex:i] objectForKey:@"name"] isEqualToString:_searchStr]) { NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0]; [myTableView reloadData]; [myTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES]; [myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle]; } } }(七)圖片基本操作
點擊圖片可跳到另一個視圖,允許縮放等編輯(詳見 MRZoomScrollView)。手勢是實現縮放的核心:雙指拖拉為縮放、雙指點擊為自動縮放、單指點擊退出。
// 加入雙擊手勢 UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)]; [doubleTapGesture setNumberOfTapsRequired:2]; [imageView addGestureRecognizer:doubleTapGesture]; #pragma mark - Zoom methods - (void)handleDoubleTap:(UIGestureRecognizer *)gesture { float newScale = self.zoomScale * 1.5; CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gesture locationInView:gesture.view]]; [self zoomToRect:zoomRect animated:YES]; } - (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center { CGRect zoomRect; zoomRect.size.height = self.frame.size.height / scale; zoomRect.size.width = self.frame.size.width / scale; zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0); zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0); return zoomRect; }至此,這篇簡單的教程就結束了,希望對你有所收穫。學習的路上,與君共勉。
投票連結:https://vote.blog.csdn.net/Article/Details?articleid=31768677