2014-12-16 3 views
3

이 질문은 여러 번 답변되었지만 행운이없는 모든 답변을 시도했습니다. 나는 근본적으로 잘못된 것을하고 있다고 생각하지 않지만 여기서 뭔가 잘못 될 것입니다.AFNetworking 2 - 이미지 업로드 - 요청하지 못했습니다 : 지원되지 않는 미디어 유형 (415)

다음 코드를 사용하여 PNG 파일을 tinypng.com에 업로드합니다. 지금까지 업로드 자체가 작동하는 것을 볼 수 있지만 다음과 같은 오류 메시지가 나타납니다. 요청 실패 : 지원되지 않는 미디어 유형 (415)

사용하는 이미지가 JPEG로로드 된 다음 크기가 조정되고 PNG 형식으로 변환됩니다. 저장된 파일은 괜찮습니다. 이제 디스크에 저장하기 전에 TinyPNG API로 보내주기를 원합니다.

누구든지 잘못된 생각이나 서비스 경험이 있으면 알려 주시기 바랍니다. 미리 감사드립니다.

자세한 오류 메시지

Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unsupported media type (415)" 
UserInfo=0x6000000e4900 { 
    com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x600000220200> { URL: https://api.tinypng.com/shrink } 
    { 
     status code: 415, headers { 
      Connection = "keep-alive"; 
      "Content-Length" = 77; 
      "Content-Type" = "application/json; charset=utf-8"; 
      Date = "Tue, 16 Dec 2014 20:24:16 GMT"; 
      Server = "Apache/2"; 
      "Strict-Transport-Security" = "max-age=31536000"; 
      "X-Powered-By" = "Voormedia (voormedia.com/jobs)"; 
     } 
    }, 
    NSErrorFailingURLKey=https://api.tinypng.com/shrink, 
    com.alamofire.serialization.response.error.data=<7b226572 726f7222 3a224261 64536967 6e617475 
    7265222c 226d6573 73616765 223a2244 6f657320 6e6f7420 61707065 61722074 6f206265 20612050 
    4e47206f 72204a50 45472066 696c6522 7d>, 
    NSLocalizedDescription=Request failed: unsupported media type (415) 
} 

코드는 나는 그것을 작동있어 TinyPNG에서 Mattijs의 지원으로

-(void) uploadImage:(NSImage *)image { 

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:TINY_PNG_URL]]; 

    CGImageRef cgRef = [image CGImageForProposedRect:NULL 
              context:nil 
               hints:nil]; 
    NSBitmapImageRep *newRep = [[NSBitmapImageRep alloc] initWithCGImage:cgRef]; 
    [newRep setSize:[image size]]; // if you want the same resolution 
    NSData *imageData = [newRep representationUsingType:NSPNGFileType properties:nil]; 

    NSDictionary *parameters = @{@"username": USERNAME, @"password" : PASSWORD}; 

    AFHTTPRequestOperation *operation = [manager POST:@"" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 

     //append image 
     [formData appendPartWithFileData:imageData 
            name:@"filename" 
           fileName:@"photo.png" 
           mimeType:@"image/png"]; 

    } success:^(AFHTTPRequestOperation *operation, id responseObject) { 
     NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject); 

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"Error: %@ ***** %@", operation.responseString, error); 
    }]; 

    [operation start]; 
} 

답변

5

를 사용! 감사합니다 Mattijs!

문제는 TinyPNG API가 요청 본문이 원래 데이터에 사용 된 다중 파트 양식 데이터 본문의 경우가 아닌 이미지 데이터 만 포함 할 것으로 예상했기 때문입니다.

내 작업 솔루션은 다음과 같습니다

-(void) uploadImage:(NSImage *)image { 

    NSData *imageData = [self PNGRepresentationOfImage:image]; 

    NSURL *url = [NSURL URLWithString:TINY_PNG_URL]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    [request setHTTPMethod:@"POST"]; 
    [request setHTTPBody:imageData]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
    [request setValue:@"image/png" forHTTPHeaderField:@"Content-Type"]; 

    NSString *authStr = [NSString stringWithFormat:@"%@:%@", USERNAME, PASSWORD]; 
    NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding]; 
    NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]]; 
    [request setValue:authValue forHTTPHeaderField:@"Authorization"]; 

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    operation.responseSerializer = [AFJSONResponseSerializer serializer]; 
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id result) { 
     NSLog(@"Success: %@ ***** %@", operation.responseString, result); 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"Error: %@ ***** %@", operation.responseString, error); 
    }]; 
    [operation start]; 
} 
관련 문제