自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

iOS使用UITableView實現(xiàn)的富文本編輯器

移動開發(fā) iOS
本文介紹iOS使用UITableView實現(xiàn)的富文本編輯器。

前言

公司最近做一個項目,其中有一個模塊是富文本編輯模塊,之前沒做個類似的功能模塊,本來以為這個功能很常見應該會有已經(jīng)造好的輪子,或許我只要找到輪子,研究下輪子,然后修改打磨輪子,這件事就八九不離十了。不過,還是 too young to simple 了,有些事,還是得自己去面對的,或許這就叫做成長,感覺最近一年,對于編程這件事,更多了一點熱愛,我感覺我不配過只會復制粘貼代碼的人生,編程需要有挑戰(zhàn)。所以,遇到困難,保持一份正念,路其實就在腳下,如果沒有困難,那就制造困哪,迎難而上,人生沒有白走的路,每一步都算數(shù),毒雞湯就到此為止,下面是干貨了。

結(jié)果

沒圖沒真相,下面是幾張實現(xiàn)的效果圖

實現(xiàn)的功能包含了:

  • 編輯器文字編輯
  • 編輯器圖片編輯
  • 編輯器圖文混排編輯
  • 編輯器圖片上傳,帶有進度和失敗提示,可以重新上傳操作
  • 編輯器模型轉(zhuǎn)換為HTML格式內(nèi)容
  • 配套的Java實現(xiàn)的服務器

以及客戶端代碼開源托管地址:RichTextEditDemo

還有java實現(xiàn)的文件服務器代碼開源托管地址:javawebserverdemo 

 

 

調(diào)研分析

基本上有以下幾種的實現(xiàn)方案:

  1. UITextView結(jié)合NSAttributeString實現(xiàn)圖文混排編輯,這個方案可以在網(wǎng)上找到對應的開源代碼,比如 SimpleWord 的實現(xiàn)就是使用這種方式,不過缺點是圖片不能有交互,比如說在圖片上添加進度條,添加上傳失敗提示,圖片點擊事件處理等等都不行,如果沒有這種需求那么可以選擇這種方案。
  2. 使用WebView通過js和原生的交互實現(xiàn),比如 WordPress-Editor 、RichTextDemo ,主要的問題就是性能不夠好,還有需要你懂得前端知識才能上手。
  3. 使用CoreText或者TextKit,這種也有實現(xiàn)方案的開源代碼,比如說這個 YYText ,這個很有名氣,不過他使用的圖片插入編輯圖片的位置是固定的,文字是圍繞著圖片,所以這種不符合我的要求,如果要使用這種方案,那修改的地方有很多,并且CoreText/TextKit使用是有一定的門檻的。
  4. 使用UITableView結(jié)合UITextView的假實現(xiàn),主要的思路是每個Cell是一個文字輸入的UITextView或者是用于顯示圖片使用的UITextView,圖片顯示之所以是選擇UITextView是因為圖片位置需要有輸入光標,所以使用UITextView結(jié)合NSAttributeString的方式正好可以實現(xiàn)這個功能。圖片和文字混排也就是顯示圖片的Cell和顯示文字的Cell混排就可以實現(xiàn)了,主要的工作量是處理光標位置輸入以及處理光標位置刪除。

選型定型

前面三種方案都有了開源的實現(xiàn),不過都不滿足需要,只有第二種方案會比較接近一點,不過WebView結(jié)合JS的操作確實是性能不夠好,內(nèi)存占用也比較高, WordPress-Editor 、RichTextDemo ,這兩種方法實現(xiàn)的編輯器會明顯的感覺到不夠流暢,并且離需要還有挺大的距離,所有沒有選擇在這基礎上進行二次開發(fā)。第三種方案在網(wǎng)上有比較多的人推薦,不過我想他們大概也只是推薦而已,真正實現(xiàn)起來需要花費大把的時間,需要填的坑有很多,考慮到時間有限,以及項目的進度安排,這個坑我就沒有去踩了。

我最終選擇的是第四種方案,這種方案好的地方就是UITableView、UITextView都是十分熟悉的組件,使用組合的模式通過以上的分析,理論上是沒有問題的,并且,UITableView有復用Cell的優(yōu)勢,所以時間性能和空間性能應該是不差的。

實現(xiàn)細節(jié)分析

使用UITableView集合UITextView的這種方案有很多細節(jié)需要注意

  1. Cell中添加UITextView,文字輸入換行或者超過一行Cell高度自動伸縮處理
  2. Cell中添加UITextView顯示圖片的處理
  3. 光標處刪除和添加圖片的處理,換行的處理

需要解決問題,好的是有些是已經(jīng)有人遇到并且解決的,其他的即使其他人沒有遇到過,作為***個吃螃蟹的人,我們詳細的去分析下其實也不難

1.這個問題剛好有人遇到過,這里就直接發(fā)鏈接了iOS UITextView 輸入內(nèi)容實時更新cell的高度

實現(xiàn)上面效果的基本原理是:

1.在 cell 中設置好 text view 的 autolayout,讓 cell 可以根據(jù)內(nèi)容自適應大小

2.text view 中輸入內(nèi)容,根據(jù)內(nèi)容更新 textView 的高度

3.調(diào)用 tableView 的 beginUpdates 和 endUpdates,重新計算 cell 的高度

4.將 text view 更新后的數(shù)據(jù)保存,以免 table view 滾動超過一屏再滾回來 text view 中的數(shù)據(jù)又不刷新成原來的數(shù)據(jù)了。

2.這個問題很簡單,使用屬性文字就行了,下面直接貼代碼了

NSAttributedString結(jié)合NSTextAttachment就行了

  1. /** 
  2.  顯示圖片的屬性文字 
  3.  */ 
  4. - (NSAttributedString*)attrStringWithContainerWidth:(NSInteger)containerWidth { 
  5.     if (!_attrString) { 
  6.         CGFloat showImageWidth = containerWidth - MMEditConfig.editAreaLeftPadding - MMEditConfig.editAreaRightPadding - MMEditConfig.imageDeltaWidth; 
  7.         NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init]; 
  8.         CGRect rect = CGRectZero; 
  9.         rect.size.width = showImageWidth; 
  10.         rect.size.height = showImageWidth * self.image.size.height / self.image.size.width; 
  11.         textAttachment.bounds = rect; 
  12.         textAttachment.image = self.image; 
  13.  
  14.         NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment]; 
  15.         NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@""]; 
  16.         [attributedString insertAttributedString:attachmentString atIndex:0]; 
  17.         _attrString = attributedString; 
  18.  
  19.         // 設置Size 
  20.         CGRect tmpImageFrame = rect; 
  21.         tmpImageFrame.size.height += MMEditConfig.editAreaTopPadding + MMEditConfig.editAreaBottomPadding; 
  22.         _imageFrame = tmpImageFrame; 
  23.     } 
  24.     return _attrString; 
  25.  

3.這個問題比較棘手,我自己也是先把可能的情況列出來,然后一個一個分支去處理這些情況,不難就是麻煩,下面的文本是我寫在 備忘錄 上的情況分析,- [x] 這種標識這種情況已經(jīng)實現(xiàn),- [ ] 這種標識暫時未實現(xiàn),后面這部分會進行優(yōu)化,主要的工作已經(jīng)完成了,優(yōu)化的工作量不會很大了。 

UITableView實現(xiàn)的編輯器

return換行情況分析:
- [x] text節(jié)點:不處理  
- [x] Image節(jié)點-前面:上面是text,光標移動到上面一行,并且在***添加一個換行,定位光標在***將
- [x] Image節(jié)點-前面:上面是圖片或者空,在上面添加一個Text節(jié)點,光標移動到上面一行,
- [x] Image節(jié)點-后面:下面是圖片或者空,在下面添加一個Text節(jié)點,光標移動到下面一行,
- [x] Image節(jié)點-后面:下面是text,光標移動到下面一行,并且在最前面添加一個換行,定位光標在最前面

Delete情況分析:  
- [x] Text節(jié)點-當前的Text不為***面-:上面是圖片,定位光標到上面圖片的***
- [x] Text節(jié)點-當前的Text不為***面-:上面是Text,合并當前Text和上面Text  這種情況不存在,在圖片刪除的時候進行合并
- [x] Text節(jié)點-當前的Text不為***面-:上面是空,不處理
- [x] Text節(jié)點-當前的Text為***面-沒有其他元素(***個)-:不處理
- [x] Text節(jié)點-當前的Text為***面-有其他元素-:刪除這一行,定位光標到下面圖片的***
- [x] Text節(jié)點-當前的Text不為空-后面-:正常刪除
- [x] Text節(jié)點-當前的Text為空-后面-:正常刪除,和第三種情況:為空的情況處理一樣

- [x] Image節(jié)點-前面-上面為Text(不為空)/Image定位到上面元素的后面
- [x] Image節(jié)點-前面-上面為Text(為空):刪除上面Text節(jié)點
- [x] Image節(jié)點-前面-上面為空:不處理
- [ ] Image節(jié)點-后面-上面為空(***個位置)-列表只有一個元素:添加一個Text節(jié)點,刪除當前Image節(jié)點,光標放在添加的Text節(jié)點上 ****TODO:上面元素不處于顯示區(qū)域不可定位****
- [x] Image節(jié)點-后面-上面為空(***個位置)-列表多于一個元素:刪除當前節(jié)點,光標放在后面元素之前
- [x] Image節(jié)點-后面-上面為圖片:刪除Image節(jié)點,定位到上面元素的后面
- [x] Image節(jié)點-后面-上面為Text-下面為圖片或者空:刪除Image節(jié)點,定位到上面元素的后面
- [x] Image節(jié)點-后面-上面為Text-下面為Text:刪除Image節(jié)點,合并下面的Text到上面,刪除下面Text節(jié)點,定位到上面元素的后面

圖片節(jié)點添加文字的情況分析:
- [ ] 前面輸入文字
- [ ] 后面輸入文字

插入圖片的情況分析:
- [x] activeIndex是Image節(jié)點-后面:下面添加一個圖片節(jié)點
- [x] activeIndex是Image節(jié)點-前面:上面添加一個圖片節(jié)點
- [x] activeIndex是Text節(jié)點:拆分光標前后內(nèi)容插入一個圖片節(jié)點和Text節(jié)點
- [x] 圖片插入之后更新 activeIndexPath 

基本上分析就到此為止了,talk is cheap, show me code,下面就是代碼實現(xiàn)了。

代碼實現(xiàn)

編輯模塊

文字輸入框的Cell實現(xiàn)

下面是文字輸入框的Cell的主要代碼,包含了

  1. 初始設置文字編輯Cell的高度、文字內(nèi)容、是否顯示Placeholder
  2. 在 UITextViewDelegate 回調(diào)方法 textViewDidChange 中處理Cell的高度自動拉伸
  3. 刪除的回調(diào)方法中處理前面刪除和后面刪除,刪除回調(diào)的代理方法是繼承 UITextView 重寫 deleteBackward 方法進行的回調(diào),具體的可以額查看 MMTextView 這個類的實現(xiàn),很簡單的一個實現(xiàn)。
  1. @implementation MMRichTextCell 
  2. // ... 
  3. - (void)updateWithData:(id)data indexPath:(NSIndexPath*)indexPath { 
  4.     if ([data isKindOfClass:[MMRichTextModel class]]) { 
  5.         MMRichTextModel* textModel = (MMRichTextModel*)data; 
  6.         _textModel = textModel; 
  7.  
  8.         // 重新設置TextView的約束 
  9.         [self.textView mas_remakeConstraints:^(MASConstraintMaker *make) { 
  10.             make.left.top.right.equalTo(self); 
  11.             make.bottom.equalTo(self).priority(900); 
  12.             make.height.equalTo(@(textModel.textFrame.size.height)); 
  13.         }]; 
  14.         // Content 
  15.         _textView.text = textModel.textContent; 
  16.         // Placeholder 
  17.         if (indexPath.row == 0) { 
  18.             self.textView.showPlaceHolder = YES; 
  19.         } else { 
  20.             self.textView.showPlaceHolder = NO
  21.         } 
  22.     } 
  23.  
  24. - (void)beginEditing { 
  25.     [_textView becomeFirstResponder]; 
  26.  
  27.     if (![_textView.text isEqualToString:_textModel.textContent]) { 
  28.         _textView.text = _textModel.textContent; 
  29.  
  30.         // 手動調(diào)用回調(diào)方法修改 
  31.         [self textViewDidChange:_textView]; 
  32.     } 
  33.  
  34.     if ([self curIndexPath].row == 0) { 
  35.         self.textView.showPlaceHolder = YES; 
  36.     } else { 
  37.         self.textView.showPlaceHolder = NO
  38.     } 
  39.  
  40. #pragma mark - ......::::::: UITextViewDelegate :::::::...... 
  41.  
  42. - (void)textViewDidChange:(UITextView *)textView { 
  43.     CGRect frame = textView.frame; 
  44.     CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT); 
  45.     CGSize size = [textView sizeThatFits:constraintSize]; 
  46.  
  47.     // 更新模型數(shù)據(jù) 
  48.     _textModel.textFrame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height); 
  49.     _textModel.textContent = textView.text; 
  50.     _textModel.selectedRange = textView.selectedRange; 
  51.     _textModel.isEditing = YES; 
  52.  
  53.     if (ABS(_textView.frame.size.height - size.height) > 5) { 
  54.  
  55.         // 重新設置TextView的約束 
  56.         [self.textView mas_remakeConstraints:^(MASConstraintMaker *make) { 
  57.             make.left.top.right.equalTo(self); 
  58.             make.bottom.equalTo(self).priority(900); 
  59.             make.height.equalTo(@(_textModel.textFrame.size.height)); 
  60.         }]; 
  61.  
  62.         UITableView* tableView = [self containerTableView]; 
  63.         [tableView beginUpdates]; 
  64.         [tableView endUpdates]; 
  65.     } 
  66.  
  67. - (BOOL)textViewShouldBeginEditing:(UITextView *)textView { 
  68.     textView.inputAccessoryView = [self.delegate mm_inputAccessoryView]; 
  69.     if ([self.delegate respondsToSelector:@selector(mm_updateActiveIndexPath:)]) { 
  70.         [self.delegate mm_updateActiveIndexPath:[self curIndexPath]]; 
  71.     } 
  72.     return YES; 
  73.  
  74. - (BOOL)textViewShouldEndEditing:(UITextView *)textView { 
  75.     textView.inputAccessoryView = nil; 
  76.     return YES; 
  77.  
  78. - (void)textViewDeleteBackward:(MMTextView *)textView { 
  79.     // 處理刪除 
  80.     NSRange selRange = textView.selectedRange; 
  81.     if (selRange.location == 0) { 
  82.         if ([self.delegate respondsToSelector:@selector(mm_preDeleteItemAtIndexPath:)]) { 
  83.             [self.delegate mm_preDeleteItemAtIndexPath:[self curIndexPath]]; 
  84.         } 
  85.     } else { 
  86.         if ([self.delegate respondsToSelector:@selector(mm_PostDeleteItemAtIndexPath:)]) { 
  87.             [self.delegate mm_PostDeleteItemAtIndexPath:[self curIndexPath]]; 
  88.         } 
  89.     } 
  90.  
  91. @end  

顯示圖片Cell的實現(xiàn)

下面顯示圖片Cell的實現(xiàn),主要包含了

  1. 初始設置文字編輯Cell的高度、圖片顯示內(nèi)容
  2. 在 UITextViewDelegate 回調(diào)方法 shouldChangeTextInRange 中處理換行和刪除,這個地方的刪除和Text編輯的Cell不一樣,所以在這邊做了特殊的處理,具體看一看 shouldChangeTextInRange 這個方法的處理方式。
  3. 處理圖片上傳的進度回調(diào)、失敗回調(diào)、成功回調(diào)
  1. @implementation MMRichImageCell 
  2. // 省略部否代碼... 
  3. - (void)updateWithData:(id)data { 
  4.     if ([data isKindOfClass:[MMRichImageModel class]]) { 
  5.         MMRichImageModel* imageModel = (MMRichImageModel*)data; 
  6.         // 設置舊的數(shù)據(jù)delegate為nil 
  7.         _imageModel.uploadDelegate = nil; 
  8.         _imageModel = imageModel; 
  9.         // 設置新的數(shù)據(jù)delegate 
  10.         _imageModel.uploadDelegate = self; 
  11.  
  12.         CGFloat width = [MMRichTextConfig sharedInstance].editAreaWidth; 
  13.         NSAttributedString* imgAttrStr = [_imageModel attrStringWithContainerWidth:width]; 
  14.         _textView.attributedText = imgAttrStr; 
  15.         // 重新設置TextView的約束 
  16.         [self.textView mas_remakeConstraints:^(MASConstraintMaker *make) { 
  17.             make.left.top.right.equalTo(self); 
  18.             make.bottom.equalTo(self).priority(900); 
  19.             make.height.equalTo(@(imageModel.imageFrame.size.height)); 
  20.         }]; 
  21.  
  22.         self.reloadButton.hidden = YES; 
  23.  
  24.         // 根據(jù)上傳的狀態(tài)設置圖片信息 
  25.         if (_imageModel.isDone) { 
  26.             self.progressView.hidden = NO
  27.             self.progressView.progress = _imageModel.uploadProgress; 
  28.             self.reloadButton.hidden = YES; 
  29.         } 
  30.         if (_imageModel.isFailed) { 
  31.             self.progressView.hidden = NO
  32.             self.progressView.progress = _imageModel.uploadProgress; 
  33.             self.reloadButton.hidden = NO
  34.         } 
  35.         if (_imageModel.uploadProgress > 0) { 
  36.             self.progressView.hidden = NO
  37.             self.progressView.progress = _imageModel.uploadProgress; 
  38.             self.reloadButton.hidden = YES; 
  39.         } 
  40.     } 
  41.  
  42. #pragma mark - ......::::::: UITextViewDelegate :::::::...... 
  43.  
  44. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { 
  45.     // 處理換行 
  46.     if ([text isEqualToString:@"\n"]) { 
  47.         if (range.location == 0 && range.length == 0) { 
  48.             // 在前面添加換行 
  49.             if ([self.delegate respondsToSelector:@selector(mm_preInsertTextLineAtIndexPath:textContent:)]) { 
  50.                 [self.delegate mm_preInsertTextLineAtIndexPath:[self curIndexPath]textContent:nil]; 
  51.             } 
  52.         } else if (range.location == 1 && range.length == 0) { 
  53.             // 在后面添加換行 
  54.             if ([self.delegate respondsToSelector:@selector(mm_postInsertTextLineAtIndexPath:textContent:)]) { 
  55.                 [self.delegate mm_postInsertTextLineAtIndexPath:[self curIndexPath] textContent:nil]; 
  56.             } 
  57.         } else if (range.location == 0 && range.length == 2) { 
  58.             // 選中和換行 
  59.         } 
  60.     } 
  61.  
  62.     // 處理刪除 
  63.     if ([text isEqualToString:@""]) { 
  64.         NSRange selRange = textView.selectedRange; 
  65.         if (selRange.location == 0 && selRange.length == 0) { 
  66.             // 處理刪除 
  67.             if ([self.delegate respondsToSelector:@selector(mm_preDeleteItemAtIndexPath:)]) { 
  68.                 [self.delegate mm_preDeleteItemAtIndexPath:[self curIndexPath]]; 
  69.             } 
  70.         } else if (selRange.location == 1 && selRange.length == 0) { 
  71.             // 處理刪除 
  72.             if ([self.delegate respondsToSelector:@selector(mm_PostDeleteItemAtIndexPath:)]) { 
  73.                 [self.delegate mm_PostDeleteItemAtIndexPath:[self curIndexPath]]; 
  74.             } 
  75.         } else if (selRange.location == 0 && selRange.length == 2) { 
  76.             // 處理刪除 
  77.             if ([self.delegate respondsToSelector:@selector(mm_preDeleteItemAtIndexPath:)]) { 
  78.                 [self.delegate mm_preDeleteItemAtIndexPath:[self curIndexPath]]; 
  79.             } 
  80.         } 
  81.     } 
  82.     return NO
  83.  
  84. - (BOOL)textViewShouldBeginEditing:(UITextView *)textView { 
  85.     textView.inputAccessoryView = [self.delegate mm_inputAccessoryView]; 
  86.     if ([self.delegate respondsToSelector:@selector(mm_updateActiveIndexPath:)]) { 
  87.         [self.delegate mm_updateActiveIndexPath:[self curIndexPath]]; 
  88.     } 
  89.     return YES; 
  90.  
  91. - (BOOL)textViewShouldEndEditing:(UITextView *)textView { 
  92.     textView.inputAccessoryView = nil; 
  93.     return YES; 
  94.  
  95.  
  96. #pragma mark - ......::::::: MMRichImageUploadDelegate :::::::...... 
  97.  
  98. // 上傳進度回調(diào) 
  99. - (void)uploadProgress:(float)progress { 
  100.     dispatch_async(dispatch_get_main_queue(), ^{ 
  101.         [self.progressView setProgress:progress]; 
  102.     }); 
  103.  
  104. // 上傳失敗回調(diào) 
  105. - (void)uploadFail { 
  106.     [self.progressView setProgress:0.01f]; 
  107.     self.reloadButton.hidden = NO
  108.  
  109. // 上傳完成回調(diào) 
  110. - (void)uploadDone { 
  111.     [self.progressView setProgress:1.0f]; 
  112.  
  113.  
  114. @end  

圖片上傳模塊

圖片上傳模塊中,上傳的元素和上傳回調(diào)抽象了對應的協(xié)議,圖片上傳模塊是一個單利的管理類,管理進行中的上傳元素和排隊中的上傳元素,

圖片上傳的元素和上傳回調(diào)的抽象協(xié)議

  1. @protocol UploadItemCallBackProtocal <NSObject> 
  2.  
  3. - (void)mm_uploadProgress:(float)progress; 
  4. - (void)mm_uploadFailed; 
  5. - (void)mm_uploadDone:(NSString*)remoteImageUrlString; 
  6.  
  7. @end 
  8.  
  9. @protocol UploadItemProtocal <NSObject> 
  10.  
  11. - (NSData*)mm_uploadData; 
  12. - (NSURL*)mm_uploadFileURL; 
  13.  
  14. @end  

圖片上傳的管理類

圖片上傳使用的是 NSURLSessionUploadTask 類處理

  1. 在 completionHandler 回調(diào)中處理結(jié)果
  2. 在NSURLSessionDelegate 的方法 URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: 中處理上傳進度
  3. 在NSURLSessionDelegate 的方法 URLSession:task:didCompleteWithError: 中處理失敗

上傳管理類的關鍵代碼如下:

  1. @interface MMFileUploadUtil () <NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate> 
  2. @property (strong,nonatomic) NSURLSession * session; 
  3. @property (nonatomic, strong) NSMutableArray* uploadingItems; 
  4. @property (nonatomic, strong) NSMutableDictionary* uploadingTaskIDToUploadItemMap; 
  5. @property (nonatomic, strong) NSMutableArray* todoItems; 
  6.  
  7. @property (nonatomic, assign) NSInteger maxUploadTask; 
  8. @end 
  9.  
  10. @implementation MMFileUploadUtil 
  11.  
  12. - (void)addUploadItem:(id<UploadItemProtocal, UploadItemCallBackProtocal>)uploadItem { 
  13.     [self.todoItems addObject:uploadItem]; 
  14.     [self startNextUploadTask]; 
  15.  
  16. - (void)startNextUploadTask { 
  17.     if (self.uploadingItems.count < _maxUploadTask) { 
  18.         // 添加下一個任務 
  19.         if (self.todoItems.count > 0) { 
  20.             id<UploadItemProtocal, UploadItemCallBackProtocal> uploadItem = self.todoItems.firstObject; 
  21.             [self.uploadingItems addObject:uploadItem]; 
  22.             [self.todoItems removeObject:uploadItem]; 
  23.  
  24.             [self uploadItem:uploadItem]; 
  25.         } 
  26.     } 
  27.  
  28. - (void)uploadItem:(id<UploadItemProtocal, UploadItemCallBackProtocal>)uploadItem { 
  29.     NSMutableURLRequest * request = [self TSuploadTaskRequest]; 
  30.  
  31.     NSData* uploadData = [uploadItem mm_uploadData]; 
  32.     NSData* totalData = [self TSuploadTaskRequestBody:uploadData]; 
  33.  
  34.     __block NSURLSessionUploadTask * uploadtask = nil; 
  35.     uploadtask = [self.session uploadTaskWithRequest:request fromData:totalData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
  36.         NSString* result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
  37.         NSLog(@"completionHandler  %@", result); 
  38.  
  39.         NSString* imgUrlString = @""
  40.         NSError *JSONSerializationError; 
  41.         id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&JSONSerializationError]; 
  42.         if ([obj isKindOfClass:[NSDictionary class]]) { 
  43.             imgUrlString = [obj objectForKey:@"url"]; 
  44.         } 
  45.         // 成功回調(diào) 
  46.         // FIXME: ZYT uploadtask ??? 
  47.         id<UploadItemProtocal, UploadItemCallBackProtocal> uploadItem = [self.uploadingTaskIDToUploadItemMap objectForKey:@(uploadtask.taskIdentifier)]; 
  48.         if (uploadItem) { 
  49.             if ([uploadItem respondsToSelector:@selector(mm_uploadDone:)]) { 
  50.                 [uploadItem mm_uploadDone:imgUrlString]; 
  51.             } 
  52.             [self.uploadingTaskIDToUploadItemMap removeObjectForKey:@(uploadtask.taskIdentifier)]; 
  53.             [self.uploadingItems removeObject:uploadItem]; 
  54.         } 
  55.  
  56.         [self startNextUploadTask]; 
  57.     }]; 
  58.     [uploadtask resume]; 
  59.  
  60.     // 添加到映射中 
  61.     [self.uploadingTaskIDToUploadItemMap setObject:uploadItem forKey:@(uploadtask.taskIdentifier)]; 
  62.  
  63. #pragma mark - ......::::::: NSURLSessionDelegate :::::::...... 
  64.  
  65. -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ 
  66.     NSLog(@"didCompleteWithError = %@",error.description); 
  67.  
  68.     // 失敗回調(diào) 
  69.     if (error) { 
  70.         id<UploadItemProtocal, UploadItemCallBackProtocal> uploadItem = [self.uploadingTaskIDToUploadItemMap objectForKey:@(task.taskIdentifier)]; 
  71.         if (uploadItem) { 
  72.             if ([uploadItem respondsToSelector:@selector(mm_uploadFailed)]) { 
  73.                 [uploadItem mm_uploadFailed]; 
  74.             } 
  75.             [self.uploadingTaskIDToUploadItemMap removeObjectForKey:@(task.taskIdentifier)]; 
  76.             [self.uploadingItems removeObject:uploadItem]; 
  77.         } 
  78.     } 
  79.  
  80.     [self startNextUploadTask]; 
  81.  
  82. -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{ 
  83.     NSLog(@"bytesSent:%@-totalBytesSent:%@-totalBytesExpectedToSend:%@", @(bytesSent), @(totalBytesSent), @(totalBytesExpectedToSend)); 
  84.  
  85.     // 進度回調(diào) 
  86.     id<UploadItemProtocal, UploadItemCallBackProtocal> uploadItem = [self.uploadingTaskIDToUploadItemMap objectForKey:@(task.taskIdentifier)]; 
  87.     if ([uploadItem respondsToSelector:@selector(mm_uploadProgress:)]) { 
  88.         [uploadItem mm_uploadProgress:(totalBytesSent * 1.0f/totalBytesExpectedToSend)]; 
  89.     } 
  90.  
  91. @end  

圖片上傳的回調(diào)會通過 UploadItemCallBackProtocal 協(xié)議的實現(xiàn)方法回調(diào)到圖片編輯的模型中,更新對應的數(shù)據(jù)。圖片編輯的數(shù)據(jù)模型是 MMRichImageModel ,該模型實現(xiàn)了 UploadItemProtocal 和

  1. @implementation MMRichImageModel 
  2.  
  3. - (void)setUploadProgress:(float)uploadProgress { 
  4.     _uploadProgress = uploadProgress; 
  5.     if ([_uploadDelegate respondsToSelector:@selector(uploadProgress:)]) { 
  6.         [_uploadDelegate uploadProgress:uploadProgress]; 
  7.     } 
  8.  
  9. - (void)setIsDone:(BOOL)isDone { 
  10.     _isDone = isDone; 
  11.     if ([_uploadDelegate respondsToSelector:@selector(uploadDone)]) { 
  12.         [_uploadDelegate uploadDone]; 
  13.     } 
  14.  
  15. - (void)setIsFailed:(BOOL)isFailed { 
  16.     _isFailed = isFailed; 
  17.     if ([_uploadDelegate respondsToSelector:@selector(uploadFail)]) { 
  18.         [_uploadDelegate uploadFail]; 
  19.     } 
  20.  
  21.  
  22. #pragma mark - ......::::::: UploadItemCallBackProtocal :::::::...... 
  23. - (void)mm_uploadProgress:(float)progress { 
  24.     self.uploadProgress = progress; 
  25.  
  26. - (void)mm_uploadFailed { 
  27.     self.isFailed = YES; 
  28.  
  29. - (void)mm_uploadDone:(NSString *)remoteImageUrlString { 
  30.     self.remoteImageUrlString = remoteImageUrlString; 
  31.     self.isDone = YES; 
  32.  
  33.  
  34. #pragma mark - ......::::::: UploadItemProtocal :::::::...... 
  35. - (NSData*)mm_uploadData { 
  36.     return UIImageJPEGRepresentation(_image, 0.6); 
  37.  
  38. - (NSURL*)mm_uploadFileURL { 
  39.     return nil; 
  40.  
  41. @end  

內(nèi)容處理模塊

最終是要把內(nèi)容序列化然后上傳到服務端的,我們的序列化方案是轉(zhuǎn)換為HTML,內(nèi)容處理模塊主要包含了以下幾點:

  • 生成HTML格式的內(nèi)容
  • 驗證內(nèi)容是否有效,判斷圖片時候全部上傳成功
  • 壓縮圖片
  • 保存圖片到本地

這部分收尾的工作比較的簡單,下面是實現(xiàn)代碼:

  1. #define kRichContentEditCache      @"RichContentEditCache" 
  2.  
  3.  
  4. @implementation MMRichContentUtil 
  5.  
  6. + (NSString*)htmlContentFromRichContents:(NSArray*)richContents { 
  7.     NSMutableString *htmlContent = [NSMutableString string]; 
  8.  
  9.     for (int i = 0; i< richContents.count; i++) { 
  10.         NSObject* content = richContents[i]; 
  11.         if ([content isKindOfClass:[MMRichImageModel class]]) { 
  12.             MMRichImageModel* imgContent = (MMRichImageModel*)content; 
  13.             [htmlContent appendString:[NSString stringWithFormat:@"<img src=\"%@\" width=\"%@\" height=\"%@\" />", imgContent.remoteImageUrlString, @(imgContent.image.size.width), @(imgContent.image.size.height)]]; 
  14.         } else if ([content isKindOfClass:[MMRichTextModel class]]) { 
  15.             MMRichTextModel* textContent = (MMRichTextModel*)content; 
  16.             [htmlContent appendString:textContent.textContent]; 
  17.         } 
  18.  
  19.         // 添加換行 
  20.         if (i != richContents.count - 1) { 
  21.             [htmlContent appendString:@"<br />"]; 
  22.         } 
  23.     } 
  24.  
  25.     return htmlContent; 
  26.  
  27. + (BOOL)validateRichContents:(NSArray*)richContents { 
  28.     for (int i = 0; i< richContents.count; i++) { 
  29.         NSObject* content = richContents[i]; 
  30.         if ([content isKindOfClass:[MMRichImageModel class]]) { 
  31.             MMRichImageModel* imgContent = (MMRichImageModel*)content; 
  32.             if (imgContent.isDone == NO) { 
  33.                 return NO
  34.             } 
  35.         } 
  36.     } 
  37.     return YES; 
  38.  
  39. + (UIImage*)scaleImage:(UIImage*)originalImage { 
  40.     float scaledWidth = 1242; 
  41.     return [originalImage scaletoSize:scaledWidth]; 
  42.  
  43. + (NSString*)saveImageToLocal:(UIImage*)image { 
  44.     NSString *path=[self createDirectory:kRichContentEditCache]; 
  45.     NSData* data = UIImageJPEGRepresentation(image, 1.0); 
  46.     NSString *filePath = [path stringByAppendingPathComponent:[self.class genRandomFileName]]; 
  47.     [data writeToFile:filePath atomically:YES]; 
  48.     return filePath; 
  49.  
  50. // 創(chuàng)建文件夾 
  51. + (NSString *)createDirectory:(NSString *)path { 
  52.     BOOL isDir = NO
  53.     NSString *finalPath = [CACHE_PATH stringByAppendingPathComponent:path]; 
  54.  
  55.     if (!([[NSFileManager defaultManager] fileExistsAtPath:finalPath 
  56.                                                isDirectory:&isDir] 
  57.           && isDir)) 
  58.     { 
  59.         [[NSFileManager defaultManager] createDirectoryAtPath:finalPath 
  60.                                  withIntermediateDirectories :YES 
  61.                                                   attributes :nil 
  62.                                                        error :nil]; 
  63.     } 
  64.  
  65.     return finalPath; 
  66.  
  67. + (NSString*)genRandomFileName { 
  68.     NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970]; 
  69.     uint32_t random = arc4random_uniform(10000); 
  70.     return [NSString stringWithFormat:@"%@-%@.png", @(timeStamp), @(random)]; 
  71.  
  72. @end  

總結(jié)

這個功能從選型定型到實現(xiàn)大概花費了3天的時間,因為時間原因,有很多地方優(yōu)化的不到位,如果看官有建議意見希望給我留言,我會繼續(xù)完善,或者你有時間歡迎加入這個項目,可以一起做得更好,代碼開源看下面的鏈接。

代碼托管位置

客戶端代碼開源托管地址:RichTextEditDemo

java實現(xiàn)的文件服務器代碼開源托管地址:[javawebserverdemo] (http://git.oschina.net/dhar/javawebdemo)

參考鏈接

責任編輯:龐桂玉 來源: aron1992的博客
相關推薦

2023-04-17 11:03:52

富文本編輯器MTE

2013-11-18 10:08:56

工具免費編程工具

2016-09-23 20:30:54

Javascriptuiwebview富文本編輯器

2023-05-11 07:34:36

Yjs協(xié)同編輯

2022-03-11 08:00:49

編輯器框架Draft.js

2012-08-10 10:47:45

JavaScript

2018-01-05 14:48:03

前端JavaScript富文本編輯器

2022-04-13 07:38:50

富文本編輯器設置表格列寬

2021-01-07 11:00:59

Sed文本編輯器Linux

2020-12-23 22:25:11

Vi文本編輯器Unix

2020-04-09 19:07:12

Vuetiptap前端

2010-03-24 09:20:07

CentOS vi編輯

2022-02-15 09:00:18

Vue編輯器字符串

2021-01-13 13:29:06

文本編輯器Atom開源

2021-01-21 16:03:15

Java文本編輯器編程語言

2021-01-13 19:13:57

Atom文本編輯器

2020-12-29 06:34:55

KDE Plasma文本編輯器

2022-05-13 15:32:11

GNOME文本編輯器

2020-12-20 08:49:01

gedit文本編輯器GNOME

2021-01-08 13:56:50

LinuxJOE文本編輯器
點贊
收藏

51CTO技術棧公眾號