在服务器上上传多个图像有时会失败,有时会工作ios sdk

时间:2014-12-22 07:28:14

标签: web-services ios7 image-uploading

我正在调用一种Web服务方法来上传图像以及其他帖子参数。 我将图像数据转换为base64字符串,如果是多个图像,我使用逗号分隔的base64字符串。有时其他帖子参数在服务器上无法到达,有时会到达。 如果我上传1或2个小图像,代码可以正常工作,但如果我选择4-5个图像,则相同的代码会失败。  post参数中的base64字符串长度是否有任何限制?什么是最好的解决方案?

转换为base64的代码

+ (NSString*) getCommaSeperatedBase64ForImages:(NSArray*)imagesArray {

NSMutableArray* final = [NSMutableArray arrayWithCapacity:0];
if(imagesArray){

    for (unsigned int i = 0;i<[imagesArray count];i++ ){
        UIImage *image = [imagesArray objectAtIndex:i];
        NSString *base64ImageString = nil;
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
            base64ImageString = [[self class] encodeToBase64String:image];
        }else{
            //iOS < 7.0
            NSData *imageData = UIImagePNGRepresentation(image);
            base64ImageString = [[NSString alloc] initWithData:imageData encoding:NSUTF8StringEncoding];
            base64ImageString = [imageData base64EncodedString];
        }
        if (base64ImageString) {
            NSLog(@"Base 64 Encoded String is %@",base64ImageString);
            [final addObject:base64ImageString];
        }
    }
}

if (final && [final count] > 0) {
   return [[self class] getCommaSeperatedString:final];
}
return nil;
}





 + (NSString *)encodeToBase64String:(UIImage *)image {
    return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

+ (NSString*)getCommaSeperatedString:(NSArray*)anArray {
    NSString *groupString = @"";
    NSInteger counter = [anArray count];
    for(unsigned int i = 0 ; i < counter; i++) {
        NSString *emailStr = [anArray objectAtIndex:i];
        if(i != counter-1)
            groupString = [groupString stringByAppendingString:[NSString stringWithFormat:@"%@,",emailStr]];
        else {
            groupString = [groupString stringByAppendingString:emailStr];
        }
    }
    return groupString;
}




    + (NSString *)encodeToBase64String:(UIImage *)image {

      return [UIImagePNGRepresentation(image)                                        base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
           }

    + (NSString*)getCommaSeperatedString:(NSArray*)anArray {
        NSString *groupString = @"";
        NSInteger counter = [anArray count];
        for(unsigned int i = 0 ; i < counter; i++) {
            NSString *emailStr = [anArray objectAtIndex:i];
            if(i != counter-1)
                groupString = [groupString stringByAppendingString:[NSString stringWithFormat:@"%@,",emailStr]];
            else {
                groupString = [groupString stringByAppendingString:emailStr];
            }
        }
        return groupString;
        }

修改更多代码 我为每个帖子参数

创建了一个带键值对的NSDictionary对象
    - (void) addNewListing:(NSDictionary*)params withCompletionBlock:(LHWebServiceCompletionBlock)block {

    @try {
        if (params == nil || [params count] == 0) {
            [self showErrorAlertWithTitle:kErrorAlertTitle andMessage:@"Failed to add listings"];
            return;

        }

        self.currentSelector = @selector(addNewListing:withCompletionBlock:);
        self.currentParams = params;
        self.completionBlock = block;

        NSString* userID = [params valueForKey:@"userID"];

        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@/%@",LH_BASE_API_URL,kAddNewListing,userID,kAPP_Key]];

        NSString *post = [NSString stringWithFormat:@"%@",[params serializeParams:[params objectForKey:@"PostParameters"]]];

        [self performURLRequestWith:url andRequestType:@"POST" andPostParamas:post];

    }
    @catch (NSException *exception) {
        NSLog(@"Exception occured in add new listing %@",[exception description]);
    }    
}




static NSString *toString(id object) {
    return [NSString stringWithFormat: @"%@", object];
}

// helper function: get the url encoded string form of any object
static NSString *urlEncode(id object) {
    NSString *string = toString(object);
    NSString *s = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                      (CFStringRef)string,
                                                                      NULL,
                                                                      (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                      kCFStringEncodingUTF8));
    return s;
}

@implementation NSDictionary (UrlEncoding)

-(NSString *)serializeParams:(NSDictionary *)params {
    /*
     Convert an NSDictionary to a query string
     */

    NSMutableArray* pairs = [NSMutableArray array];
    for (NSString* key in [params keyEnumerator]) {
        id value = [params objectForKey:key];
        if ([value isKindOfClass:[NSDictionary class]]) {
            for (NSString *subKey in value) {
                NSString* escaped_value = [value objectForKey:subKey];
                [pairs addObject:[NSString stringWithFormat:@"%@[%@]=%@", urlEncode(key), urlEncode(subKey), urlEncode(escaped_value)]];
            }
        } else if ([value isKindOfClass:[NSArray class]]) {
            for (NSString *subValue in value) {
                NSString* escaped_value = subValue;
                [pairs addObject:[NSString stringWithFormat:@"%@[]=%@", urlEncode(key), urlEncode(escaped_value)]];
            }
        } else {
            NSString* escaped_value = [params objectForKey:key];
            [pairs addObject:[NSString stringWithFormat:@"%@=%@", urlEncode(key), urlEncode(escaped_value)]];
            //[escaped_value release];
        }
    }
    return [pairs componentsJoinedByString:@"&"];
}

@end

网络服务方法

- (void)performURLRequestWith:(NSURL*)requestURL andRequestType:(NSString*)type andPostParamas:(NSString*)postData {


    @try {
        if (requestURL == nil || type == nil) {
            if (self.completionBlock) {

                NSError* error = [self generateErroWithMessage:@"Invalid URL"];
                self.completionBlock(error,nil);
            }
            return;
        }
        myURLRequest = [[NSMutableURLRequest alloc] initWithURL:requestURL];
        [myURLRequest setHTTPMethod:type];
        [myURLRequest setTimeoutInterval:kRequestTimeOut];
        if ([type isEqualToString:@"POST"]) {
            if (postData == nil) {
                NSError* error = [self generateErroWithMessage:@"Web Service Error"];
                self.completionBlock(error,nil);
            }
            //        NSString* encodedPost = [[self class] urlEncoded:postData];
            NSData *requestData = [postData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

            NSString* requestDataLengthString = [NSString stringWithFormat:@"%d",[requestData length]];
            [myURLRequest setHTTPBody:requestData];
            [myURLRequest setValue:requestDataLengthString forHTTPHeaderField:@"Content-Length"];

            NSLog(@"Post Params %@",postData);
            NSLog(@"Register URL %@",requestURL);


            //[requestData release];
            //[requestDataLengthString release];

            //self.currentConnection = [NSURLConnection connectionWithRequest:myURLRequest delegate:self];
        }

        if (self.currentConnection != nil) {
            self.currentConnection = nil;
        }
        if (async) {
            [NSURLConnection sendAsynchronousRequest:myURLRequest
                                               queue:[NSOperationQueue mainQueue]
                                   completionHandler:^(NSURLResponse *response, NSData *serverData, NSError *connectionError) {
                                       NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                                       if ([serverData length] >0 && connectionError == nil && [httpResponse statusCode] == 200)
                                       {
                                           if ([serverData length] > 0 && connectionError == nil){
                                               [self connection:nil didReceiveData:serverData];
                                               // DO YOUR WORK HERE
                                               [self connectionDidFinishLoading:nil];
                                           }

                                       }
                                   }];
            async = NO;
        }
        else {
            self.currentConnection = [NSURLConnection connectionWithRequest:myURLRequest delegate:self];
        }

    }
    @catch (NSException *exception) {
        NSLog(@"Exception occured %@",[exception description]);
    }



}

如果我使用1或2张图片,则上述代码有效,但如果使用4-5图像服务器发送给我,则其他帖子参数的值为null。

0 个答案:

没有答案