您的位置:首页 > 移动开发 > IOS开发

iOS 使用AFN for 循环上传多张图片至服务器,用户手机项目上面的图片顺序查看

2016-11-28 09:45 633 查看
AFN 是非常强大的网络请求工具,作为ios 开发者应该都接触或者使用这个第三方,但是项目中遇到的问题是,客户端上传图片给服务器,服务器再推给我接收这个图片的对象,但是要求是对象接受的公告也应该是我发送图片的那个顺序,而都知道AFN是异步的,服务器不能够判断我客户端图片的顺序,因此需要我改变AFN异步或者想方设法的去让图片顺序上传给服务器,for循环当然是在主线程,不多说直接上代码

    __blockNSMutableArray * accessoryArr = [[NSMutableArrayalloc]initWithCapacity:_photoMessage.count];
    if (_photoMessage.count>0)
{

原本更改过测试了一次好了,但是现在发现是我自测不仔细造成的,考虑到线程处理太过麻烦(关键是复杂的自己不熟悉)只能使用笨方法

    if (_photoMessage.count>0)
{

        //防止数组越界
        NSMutableArray * upLoadArr = [[NSMutableArrayalloc]initWithCapacity:accessoryArr.count];
        for (int i =
0; i<_photoMessage.count;
i++) {

            //初始化一个数组用于替换图片的顺序
          [upLoadArr addObject:@(i)];
            [DataRequestgetRequestWithPh
4000
oto
:_photoMessage[i]
withGetImgInt:i
success:^(id result) {
                NSDictionary*resultDic = (NSDictionary*)result;
                NSMutableDictionary * UpphotoDic = [[NSMutableDictionaryalloc]init];
                NSDictionary * singlePhotoDic = resultDic[@"datas"];
                [UpphotoDic setObject:singlePhotoDic[@"fileName"]
forKey:@"fileName"];
                [UpphotoDic setObject:singlePhotoDic[@"size"]
forKey:@"fileSize"];
                [UpphotoDic setObject:singlePhotoDic[@"url1"]
forKey:@"fileUrl"];
                [accessoryArr addObject:@{@(i):
UpphotoDic
}];
                if (accessoryArr.count ==_photoMessage.count)
{

                                           
dispatch_async(dispatch_get_main_queue(), ^{
                    // 主线程执行:
                    for (int i =
0; i<accessoryArr.count; i++) {
                [upLoadArr replaceObjectAtIndex:[[[accessoryArr[i]
allKeys]
firstObject]
integerValue]
withObject:[[accessoryArr[i]
allValues]
firstObject]];
                    }
                                PublishNoticeModule * PNModule = [selfpublishNoticeInterface:upLoadArr];
                                //    //条件都满足的时候和服务器进行交互
                                [DataRequestgetRequestWithNoticeDic:PNModule
success:^(id result) {
                                   
NSDictionary * dic = (NSDictionary*)result;
                                   
if (dic[@"success"]) {
                                        [selfshowHubTitle:self.viewtitleText:@"发布成功"location:FULL_HEIGHT/2-80];
                                        [selfperformSelector:@selector(jumpRecentVC)
withObject:selfafterDelay:1];
                                    }
                                }
failed:^(id failResult) {
                                    [selfshowHubTitle:self.viewtitleText:@"发布失败"location:FULL_HEIGHT/2-80];
                                   
_rightBtnItem.enabled =
YES;
                                }];
                });
                }
            } failed:^(id failResult) {
                [selfshowHubTitle:self.viewtitleText:@"发布失败"location:FULL_HEIGHT/2-80];
                _rightBtnItem.enabled =
YES;
            }];
            }

/********************************/有问题
    //原子性保护,保证同时只有一个线程进入操作,从而实现数据图片上传的顺序性,原子性保护,相当于lock,这样的话,我的for循环的请求只有请求成功之后才会进入下一个请求,防止多线程同时访问导致的数据混乱,这样即可保护我上传的数据的顺序性和正确性
           
dispatch_queue_t defaultQueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
               dispatch_semaphore_t semaphore =dispatch_semaphore_create(1);
_photoMessage存放的是图片的数组

        for (int i =0;
i<
_photoMessage.count; i++) {
                   dispatch_async(defaultQueue, ^{
                       dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
                        [DataRequestgetRequestWithPhoto:_photoMessage[i]withGetImgInt:isuccess:^(id
result) {

                            NSDictionary*resultDic = (NSDictionary*)result;
                            NSMutableDictionary * UpphotoDic = [[NSMutableDictionaryalloc]init];
                            NSDictionary * singlePhotoDic = resultDic[@"datas"];
                            [UpphotoDic
setObject:singlePhotoDic[@"fileName"]forKey:@"fileName"];
                            [UpphotoDic
setObject:singlePhotoDic[@"size"]forKey:@"fileSize"];
                            [UpphotoDic
setObject:singlePhotoDic[@"url1"]forKey:@"fileUrl"];
                            [accessoryArr
addObject:@{@(i): UpphotoDic}];
                            if (accessoryArr.count ==_photoMessage.count)
{

                                NSMutableArray *uploadArr =@[].mutableCopy;
                                for (int i =0;
i<accessoryArr.
count; i++) {
                                   
NSDictionary * dic = accessoryArr[i];
                                    [uploadArraddObject:[dic.allValuesfirstObject]];
                                }
                                PublishNoticeModule * PNModule = [selfpublishNoticeInterface:uploadArr];
                                //    //条件都满足的时候和服务器进行交互
                                [DataRequestgetRequestWithNoticeDic:PNModulesuccess:^(id
result) {

                                   
NSDictionary * dic = (NSDictionary*)result;
                                   
if (dic[@"success"]) {
                                        [selfshowHubTitle:self.viewtitleText:@"发布成功"location:HEIGHT/2-80];
                                        [selfperformSelector:@selector(jumpRecentVC)withObject:selfafterDelay:1];
                                    }
                                }
failed:^(id failResult) {
                                    [selfshowHubTitle:self.viewtitleText:@"发布失败"location:HEIGHT/2-80];
                                   
_rightBtnItem.enabled =YES;
                                }];
                            }
                        } failed:^(id failResult) {
                            [selfshowHubTitle:self.viewtitleText:@"发布失败"location:HEIGHT/2-80];
                            _rightBtnItem.enabled =YES;
                        }];
                       dispatch_semaphore_signal(semaphore);
                    });
            }
    }

/********************************/

//既然for循环上传图片都处理了,那就把上传图片的代码一并奉上

+(void)getRequestWithPhoto:(UIImage*)image withGetImgInt:(NSInteger)index
success:(
SuccessBlock)success failed:(FailBlock)fail{
        AFHTTPSessionManager * manager = [AFHTTPSessionManagermanager];
        NSString * token = [[NSUserDefaultsstandardUserDefaults]objectForKey:@"token"];
        NSString * urlStr = [NSStringstringWithFormat:@"%@?ticket=%@",URL,token];//URL
此处填写ing求地址

        manager.responseSerializer.acceptableContentTypes
=[
NSSetsetWithObjects:@"application/json",@"text/json"
,
nil];
        
        [manager POST:urlStrparameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData_Nonnull
formData) {

            NSData *data ;
            if (UIImagePNGRepresentation(image)==nil)
{

                data = UIImageJPEGRepresentation(image,1);
            }else{
                data = UIImagePNGRepresentation(image);
            }
            NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
            formatter.dateFormat =@"yyyyMMddHHmmss";
           
NSString *str = [formatterstringFromDate:[NSDatedate]];
           
NSString *fileName = [NSStringstringWithFormat:@"%@%ld.png",
str,index];//将图片是当前的时间命名防止图片的重复,确保图片的唯一性

            [formData appendPartWithFileData:dataname:@"file"fileName:fileNamemimeType:@"image/png"];//将image转化成data类型,并以时间作为文件名上传至服务器,mimeType
填写的是图片的后缀

        } progress:^(NSProgress *_Nonnull
uploadProgress) {

            
        } success:^(NSURLSessionDataTask *_Nonnull
task,
id _Nullable responseObject) {
            if (success) {
                success(responseObject);//上传成功服务器所返回给我的字典
            }
        } failure:^(NSURLSessionDataTask *_Nullable
task,
NSError *_Nonnull error) {
            if (fail) {
                fail(error);
            }
        }];
};
用户接收到发布的图片之后在使用MWPhotoBrower来进行图片的预览

        NSMutableArray * noticeImageArr = [selfgetCachesAllDownImage];//
getCachesAllDownImage 用于将下载的图片存放在沙盒中进行缓存
//获取缓存里面的所有图片
-(NSMutableArray*)getCachesAllDownImage{

    NSMutableArray * photoArr = [[NSMutableArrayalloc]init];
    for (NSDictionary * fileDic in_noticeModel.attachs)
{

        NSString * path = [selfdicCaches];
        NSInteger fileType = [fileDic[@"fileType"]integerValue];
               UIImage * noticeImg =nil;
        if (fileType==1) {
            NSString *imageFilePath = [pathstringByAppendingPathComponent:fileDic[@"fileName"]];
                if ([[NSFileManagerdefaultManager]fileExistsAtPath:imageFilePath])
{

                    noticeImg = [UIImageimageWithContentsOfFile:imageFilePath];
                    if (noticeImg) {
                    [photoArr addObject:noticeImg];
                    }
            }else{
                NSURL *url = [NSURLURLWithString:fileDic[@"fileUrl"]];
                NSData *resultData = [NSDatadataWithContentsOfURL:url];
                if (resultData) {
                    noticeImg = [UIImageimageWithData:resultData];
                    BOOL success = [UIImageJPEGRepresentation(noticeImg,1)writeToFile:imageFilePath atomically:YES];
                    if (success){
                    }
                }
                if (noticeImg) {
                    [photoArr addObject:noticeImg];
                }
            }
        }
    }
    return photoArr;
}
-(NSString*)dicCaches
{
//Caches的url路径
    NSArray *cacPath =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
    NSString *cachePath = [cacPathobjectAtIndex:0];
    return cachePath;
}
//查看的图片存在的话,就显示
        if (noticeImageArr) {
            dispatch_async(dispatch_get_main_queue(),
^{

                _lookPhotoArr = [NSMutableArraynew];
                for (int i =0;
i<noticeImageArr.
count; i++) {
                    MWPhoto * photo = [MWPhotophotoWithImage:noticeImageArr[i]];
                    [_lookPhotoArraddObject:photo];
                }
                [selfhideHUD];
                if (_lookPhotoArr.count>0)
{

                    self.brower = [[MWPhotoBrowseralloc]initWithDelegate:self];
                    [self.browersetCurrentPhotoIndex:self.selectIndex];
                    self.brower.displayActionButton
=
YES;
                    self.brower.displayNavArrows
=
NO;
                    
                    [self.browersetHidesBottomBarWhenPushed:YES];
                    self.brower.zoomPhotosToFill
=
YES;
                    [self.viewaddSubview:self.brower.view];
                    [selfaddChildViewController:self.brower];
}
//MW的三个代理方法

-(NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser
*)photoBrowser{

    
    return [self.lookPhotoArrcount];
}
-(id<MWPhoto>)photoBrowser:(MWPhotoBrowser
*)photoBrowser photoAtIndex:(
NSUInteger)index{
    if (index <self.lookPhotoArr.count)
        return [self.lookPhotoArrobjectAtIndex:index];
    returnnil;
}
// 滑动执行的方法
- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index{
    NSDictionary * fileDic = [_noticeModel.attachsobjectAtIndex:index];
    if (fileDic) {
        self.titleLab.text
= fileDic[
@"fileName"];
    }
}
//获取缓存里面的所有图片
-(NSMutableArray*)getCachesAllDownImage{

    NSMutableArray * photoArr = [[NSMutableArrayalloc]init];
    for (NSDictionary * fileDic in_noticeModel.attachs)
{

        NSString * path = [selfdicCaches];
        NSInteger fileType = [fileDic[@"fileType"]integerValue];
               UIImage * noticeImg =nil;
//1
        if (fileType==1) {
//得到文件路径
            NSString *imageFilePath = [pathstringByAppendingPathComponent:fileDic[@"fileName"]];
//如果存在URL 缓存则沙盒里面直接读
                if ([[NSFileManagerdefaultManager]fileExistsAtPath:imageFilePath])
{

                    noticeImg = [UIImageimageWithContentsOfFile:imageFilePath];
                    if (noticeImg) {
                    [photoArr addObject:noticeImg];
                    }
            }else{
//如果本地不存在缓存的话直接使用dataContentsOfUrl 再使用
imageWithData转化为image

                NSURL *url = [NSURLURLWithString:fileDic[@"fileUrl"]];
                NSData *resultData = [NSDatadataWithContentsOfURL:url];
                if (resultData) {
                    noticeImg = [UIImageimageWithData:resultData];
                    BOOL success = [UIImageJPEGRepresentation(noticeImg,1)writeToFile:imageFilePath atomically:YES];
                    if (success){
                    }
                }
                if (noticeImg) {
                    [photoArr addObject:noticeImg];
                }
            }
        }
    }
    return photoArr;
}
-(NSString*)dicCaches
{
    NSArray *cacPath =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
    NSString *cachePath = [cacPathobjectAtIndex:0];
    return cachePath;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐