ReleasePostViewController.m 17.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
//
//  ReleasePostViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2016/12/9.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "ReleasePostViewController.h"
#import "HeadlineTableViewCell.h"
#import "ContentTableViewCell.h"
#import "PhotoManagerViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "MWPhotoBrowser.h"
#import "OSSHelper.h"
#import "UIImage+Fit.h"





@interface ReleasePostViewController ()<UITableViewDelegate,UITableViewDataSource,ExtensionViewTapDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,MWPhotoBrowserDelegate>

/**
 选择图片
 */
@property (nonatomic,strong) NSMutableArray *selectedImageArray;

/**
 相册图片
 */
@property (nonatomic,strong) NSMutableArray *allPhotoArray;

/**
 MWPhoto
 */
@property (nonatomic,strong) NSMutableArray *mwPhotoArray;

/**
 缩略图
 */
@property (nonatomic,strong) NSMutableArray *thumbsArray;

/**
 图片是否选中
 */
@property (nonatomic,strong) NSMutableArray *selecedSectionArray;

/**
 输入框高度
 */
@property (nonatomic,assign) CGFloat contentTextViewHeight;

@end

@implementation ReleasePostViewController


#pragma mark -渲染完成
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 30.0f;
}

#pragma mark -视图即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 0.0f;
}


#pragma mark - lazy
- (NSMutableArray *)selectedImageArray
{
    if (!_selectedImageArray) {
        _selectedImageArray = [NSMutableArray array];
    }
    return _selectedImageArray;
}

- (NSMutableArray *)selecedSectionArray
{
    if (!_selecedSectionArray) {
        _selecedSectionArray = [NSMutableArray array];
    }
    return _selecedSectionArray;
}

- (NSMutableArray *)allPhotoArray
{
94
    if (!_allPhotoArray.count) {
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        _allPhotoArray = [NSMutableArray array];
        PHFetchOptions *options = [PHFetchOptions new];
        options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
        PHFetchResult *fetchResults = [PHAsset fetchAssetsWithOptions:options];
        [fetchResults enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [_allPhotoArray addObject:obj];
        }];
        for (int i=0; i<_allPhotoArray.count; i++) {
            [self.selecedSectionArray addObject:@0];
        }
    }
    return _allPhotoArray;
}

- (NSMutableArray *)mwPhotoArray
{
111
    if (!_mwPhotoArray.count) {
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        _mwPhotoArray = [NSMutableArray array];
        UIScreen *screen = [UIScreen mainScreen];
        CGFloat scale = screen.scale;
        // Sizing is very rough... more thought required in a real implementation
        CGFloat imageSize = MAX(screen.bounds.size.width, screen.bounds.size.height) * 1.5;
        CGSize imageTargetSize = CGSizeMake(imageSize * scale, imageSize * scale);
        for (PHAsset *asset in self.allPhotoArray) {
            [_mwPhotoArray addObject:[MWPhoto photoWithAsset:asset targetSize:imageTargetSize]];
        }
    }
    return _mwPhotoArray;
}

- (NSMutableArray *)thumbsArray
{
    if (!_thumbsArray) {
        _thumbsArray = [NSMutableArray array];
        UIScreen *screen = [UIScreen mainScreen];
        CGFloat scale = screen.scale;
        // Sizing is very rough... more thought required in a real implementation
        CGFloat imageSize = MAX(screen.bounds.size.width, screen.bounds.size.height) * 1.5;
        CGSize thumbTargetSize = CGSizeMake(imageSize / 3.0 * scale, imageSize / 3.0 * scale);
        for (PHAsset *asset in self.allPhotoArray) {
            [_thumbsArray addObject:[MWPhoto photoWithAsset:asset targetSize:thumbTargetSize]];
        }
    }
    return _thumbsArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self addChildViewController];
}

#pragma mark - UI
- (void)uiConfigAction
{
    self.publishTableView.tableFooterView = [UIView new];
153 154
    [self.categoryImageView sd_setImageWithURL:[NSURL URLWithString:self.category.attachment.fileUrl] placeholderImage:REPLACEIMAGE];
    self.categoryTitleLabel.text = self.category.name;
155
    [self allPhotoArray];
156 157 158 159 160
    if (![[self class] determinePhotosPermissions]) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在iPad的“设置-隐私-相册”选项中,允许欧立方访问你的相册" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
}

#pragma mark - 图片管理
- (void)addChildViewController
{
    PhotoManagerViewController *photoManager = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"PhotoManagerViewController"];
    [self addChildViewController:photoManager];
}


#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case HeadlineCell:
        {
            HeadlineTableViewCell *titleCell = [tableView dequeueReusableCellWithIdentifier:@"HeadlineTableViewCell" forIndexPath:indexPath];
            return titleCell;
        }
            break;
        case ContentCell:
        {
            ContentTableViewCell *contentCell = [tableView dequeueReusableCellWithIdentifier:@"ContentTableViewCell" forIndexPath:indexPath];
            contentCell.delgate = self;
            PhotoManagerViewController *photo = [self.childViewControllers firstObject];
            [contentCell.contentView addSubview:photo.view];
187
            photo.view.frame = CGRectMake(contentCell.contentTextView.x, contentCell.contentTextView.bottom+10, contentCell.contentTextView.width, [self calculateImageHeight]);
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
            photo.imageArray = self.selectedImageArray;
            return contentCell;
        }
            break;
            
        default:
            break;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case HeadlineCell:
            return 44;
            break;
        case ContentCell:
        {
            return self.contentTextViewHeight + 30 + [self calculateImageHeight];
        }
            break;
            
        default:
            break;
    }
    return 0;
}


#pragma mark - 拍照
- (void)showCameraAction
{
    if ([[self class] determineCameraPermissions]) {
        UIImagePickerController *camera = [[UIImagePickerController alloc]init];
        camera.delegate = self;
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [camera setSourceType:UIImagePickerControllerSourceTypeCamera];
            camera.allowsEditing = YES;
            [self presentViewController:camera animated:YES completion:nil];
        }else {
            [XBLoadingView showHUDViewWithText:@"相机无法使用"];
        }
    }
}

#pragma mark - <UIImagePickerControllerDelegate>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    UIImage *headImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self.selectedImageArray addObject:headImage];
    [self.publishTableView reloadData];
}


#pragma mark - 相册
- (void)showPhotoAlbumAction
{
    for (int i=0; i<self.selecedSectionArray.count; i++) {
        if ([self.selecedSectionArray[i] boolValue]) {
            self.selecedSectionArray[i] = @0;
        }
    }
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;
    browser.displayNavArrows = YES;
    browser.displaySelectionButtons = YES;
    browser.alwaysShowControls = YES;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = YES;
    browser.startOnGrid = YES;
    browser.enableSwipeToDismiss = YES;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:browser];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

#pragma mark - 刷新高度
- (void)refreshHeight:(CGFloat)height
{
    self.contentTextViewHeight = height;
    [self.publishTableView reloadData];
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.mwPhotoArray.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.mwPhotoArray.count)
        return [self.mwPhotoArray objectAtIndex:index];
    return nil;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    if (index < self.thumbsArray.count)
        return [self.thumbsArray objectAtIndex:index];
    return nil;
}

- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index {
    if (self.selecedSectionArray.count) {
        return [[self.selecedSectionArray objectAtIndex:index] boolValue];
    }
    return NO;
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected  {
    [self.selecedSectionArray replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:selected]];
}

- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser {
    
    [self dismissViewControllerAnimated:YES completion:^{
        for (int i=0; i<self.selecedSectionArray.count; i++) {
            BOOL boolValue = [self.selecedSectionArray[i] boolValue];
            if (boolValue) {
                PHAsset *asset = self.allPhotoArray[i];
                [self performLoadUnderlyingImageAndNotifyWithAsset:asset targetSize:CGSizeMake(ScreenWidth, ScreenHeight)];
            }
        }
        [self.publishTableView reloadData];
    }];
}

#pragma mark - 获取选择的图片
- (void)performLoadUnderlyingImageAndNotifyWithAsset:(PHAsset *)asset targetSize:(CGSize)targetSize {
    
    PHImageManager *imageManager = [PHImageManager defaultManager];
    PHImageRequestOptions *options = [PHImageRequestOptions new];
    options.networkAccessAllowed = YES;
    options.resizeMode = PHImageRequestOptionsResizeModeFast;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    options.synchronous = false;
    [imageManager requestImageForAsset:asset targetSize:targetSize contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.selectedImageArray addObject:result];
            [self.publishTableView reloadData];
        });
    }];
}

#pragma mark - 计算选中图片显示所需高度
- (CGFloat)calculateImageHeight
{
    //默认每行显示8张图片
    CGFloat height = (ScreenWidth-40-7*20)/8;
    CGFloat interval = 20;
    CGFloat allHeight = 0;
    NSInteger number = self.selectedImageArray.count/8;
    if (self.selectedImageArray.count < 8) {
        return height;
    }else if (self.selectedImageArray.count %8 == 0) {
        allHeight = number*height + (number-1)*interval;
    }else if (number) {
        allHeight = (number+1)*height + (self.selectedImageArray.count/8)*interval;
    }
    return allHeight;
}

#pragma mark - 发表
- (IBAction)publishButtonClickAction:(UIButton *)sender {
    
357
    [self.view endEditing:YES];
358
    WS(weakSelf);
359 360 361 362
    ShowAlertView(@"提示", @"确认发表吗?", @[@"确认",@"取消"], UIAlertControllerStyleAlert, ^(NSInteger index) {
        if (index == ONE) {
            return;
        }
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
        HeadlineTableViewCell *titleCell = [weakSelf.publishTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        ContentTableViewCell *contentCell = [weakSelf.publishTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        if ([[weakSelf class] isBlankString:titleCell.titleTextField.text]) {
            [XBLoadingView showHUDViewWithText:@"标题不能为空"];return;
        }
        if ([[weakSelf class] isBlankString:contentCell.contentTextView.text]) {
            [XBLoadingView showHUDViewWithText:@"内容不能为空"];return;
        }
        WS(weakSelf);
        if (weakSelf.selectedImageArray.count) {
            [weakSelf uploadAttachments:^(NSArray *OSSKeys)  {
                [weakSelf submitPost:titleCell.titleTextField.text withContent:contentCell.contentTextView.text withAttachments:OSSKeys];
            }];
        }else {
            [weakSelf submitPost:titleCell.titleTextField.text withContent:contentCell.contentTextView.text withAttachments:nil];
        }
379
    });
380 381 382 383 384 385 386 387 388 389 390
}

#pragma mark - 上传图片附件
- (void)uploadAttachments:(void(^)(NSArray *OSSKeys))finish
{
    NSMutableArray *OSSKeyArray = [NSMutableArray array];
    for (int i=0; i<self.selectedImageArray.count; i++) {
        [OSSKeyArray addObject:[OSSHelper getOSSObjectKeyWithtype:@"png" index:i]];
    }
    XBLoadingView *loadView = [XBLoadingView showHUDViewProgressLabel:[NSString stringWithFormat:@"图片上传中:1/%ld",self.selectedImageArray.count]];
    static NSInteger number = 0;
391 392 393 394 395 396
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        for (int i=0;i<self.selectedImageArray.count;i++) {
            UIImage *image = self.selectedImageArray[i];
            NSString *ossKey = OSSKeyArray[i];
            NSData *data = UIImagePNGRepresentation(image);
397 398 399 400 401
            [OSSHelper uploadImageObjectWithKey:ossKey data:data type:OSSHelperOperationTypeSynchronous progress:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
                CGFloat totalBytesSentFloat = totalBytesSent;
                CGFloat totalBytesExpectedToSendFloat = totalBytesExpectedToSend;
                CGFloat progress = totalBytesSentFloat / totalBytesExpectedToSendFloat;
                NSLog(@"-->进度%f", progress);
402
                loadView.progress = progress;
403 404 405 406
                
            } success:^id(OSSTask *task) {
                
                number ++;
407 408 409 410 411 412 413 414 415 416
                loadView.labelText = [NSString stringWithFormat:@"图片上传中:%ld/%ld",number,self.selectedImageArray.count];
                if (number == self.selectedImageArray.count) {
                    number = 0;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [loadView hide:YES];
                        [XBLoadingView showHUDViewWithSuccessText:@"图片上传成功" completeBlock:^{
                            finish(OSSKeyArray);
                        }];
                    });
                }
417 418
                return nil;
            } error:^(NSError *error) {
419
                [XBLoadingView hideHUDViewWithDefault];
420
                [XBLoadingView showHUDViewWithText:error.localizedDescription];
421 422 423 424 425 426 427 428 429
            }];
        }
    });
}

#pragma mark - 发布帖子
- (void)submitPost:(NSString *)title withContent:(NSString *)content withAttachments:(NSArray *)OSSKeyArray
{
    TOForumTopicEntity *topic = [[TOForumTopicEntity alloc] init];
430 431 432 433 434
    topic.posterId = [Shoppersmanager manager].shoppers.employee.fid;
    topic.posterName = [Shoppersmanager manager].shoppers.employee.userName;
    topic.posterRealName = [Shoppersmanager manager].shoppers.employee.realName;
    topic.posterPosition = [Shoppersmanager manager].shoppers.employee.positionsName;
    topic.posterPicture = [Shoppersmanager manager].shoppers.employee.picture;
435
    topic.postTime = [[self class] getTimeby:0];
436
    topic.category = self.category.fid;
曹云霄's avatar
曹云霄 committed
437
    topic.backEnd = [Shoppersmanager manager].shoppers.isAdmin;
438
    topic.forumType = self.category.typeId;
439 440
    topic.title = title;
    topic.content = content;
441
    topic.bestTopic = false;
442 443
    NSMutableArray *attachments = [NSMutableArray array];
    NSString *entityId = [OSSHelper getOSSObjectKey];
444
    topic.attachmentId = entityId;
445 446 447 448 449
    for (NSString *ossKey in OSSKeyArray) {
        TOAttachmentEntity *entity = [[TOAttachmentEntity alloc] init];
        entity.entityType = @"forumTopic";
        entity.entityId = entityId;
        entity.fileUrl = [OSSHelper getCompleteImageURLWithOSSkey:ossKey];
450
        entity.fileName = ossKey;
451 452 453 454 455
        [attachments addObject:entity];
    }
    topic.attachments = (NSArray<TOAttachmentEntity>*)attachments;
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
曹云霄's avatar
曹云霄 committed
456
    [HTTP networkRequestWithURL:SERVERREQUESTURL(SUBMITTOPIC) withRequestType:ZERO withParameter:topic withReturnValueBlock:^(id returnValue) {
457 458
        
        [XBLoadingView hideHUDViewWithDefault];
曹云霄's avatar
曹云霄 committed
459
        if (RESULT(returnValue)) {
460
            [XBLoadingView showHUDViewWithSuccessText:@"发布成功" completeBlock:^{
461 462 463
                if (weakSelf.finishBlock) {
                    weakSelf.finishBlock();
                }
464 465 466
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }];
        }else {
467
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
468 469
        }
        
470
    } withFailureBlock:^(NSError *error) {
471 472 473 474 475 476 477 478
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}




@end