2016-02-25 6 views
2

Я работаю под приложением, которое должно позволять размещать изображения на стене пользователей. В начале он получает разрешение, на этом этапе все в порядке. Но когда я пытаюсь сделать почтовый запрос, ничего не публикуется. вы могли бы просто помочь решить следующую проблему. Когда пользователь выбирает кнопку изображения и нажмите пост:Как размещать изображения на странице пользователей Imgur

- (void) postActionSelected 
{ 

    NSString *title = [[self titleTextField] text]; 
    NSString *description = [[self commentTextField] text]; 

    NSData *imageData = UIImageJPEGRepresentation(self.currentImage.image, 0.5); 
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 



    [imgurServerManager uploadPhoto:imageData 
          title:title 
        description:description 
       completionBlock:^(NSString *result) { 
        dispatch_async(dispatch_get_main_queue(), ^{ 
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; 
        }); 
       } failureBlock:^(NSURLResponse *response, NSError *error, NSInteger status) { 
        dispatch_async(dispatch_get_main_queue(), ^{ 
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; 
         [[[UIAlertView alloc] initWithTitle:@"Upload Failed" 
                message:[NSString stringWithFormat:@"%@ (Status code %ld)", [error localizedDescription], (long)status] 
                delegate:nil 
              cancelButtonTitle:nil 
              otherButtonTitles:@"OK", nil] show]; 
        }); 
       }]; 

}); 

}

, а затем в ImGurServerManager это сообщение должно быть сделано:

+ (void)uploadPhoto:(NSData*)imageData 
       title:(NSString*)title 
     description:(NSString*)description 
    completionBlock:(void(^)(NSString* result))completion 
     failureBlock:(void(^)(NSURLResponse *response, NSError *error, NSInteger status))failureBlock 
{ 
    NSAssert(imageData, @"Image data is required"); 
    //NSAssert(access_token, @"Access token is required"); 

    NSString *urlString = @"https://api.imgur.com/3/upload"; 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ; 
    [request setURL:[NSURL URLWithString:urlString]]; 
    [request setHTTPMethod:@"POST"]; 

    NSMutableData *requestBody = [[NSMutableData alloc] init]; 

    NSString *boundary = @"---------------------------0983745982375409872438752038475287"; 

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; 
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"]; 

    //[request addValue:[NSString stringWithFormat:@"access_token %@", access_token] forHTTPHeaderField:@"access_token"]; 

    [requestBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] 
      dataUsingEncoding:NSUTF8StringEncoding]]; 
    [requestBody appendData:[@"Content-Disposition: attachment; name=\"image\"; filename=\".tiff\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 

    [requestBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    [requestBody appendData:[NSData dataWithData:imageData]]; 
    [requestBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 


    if (title) { 
     [requestBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [requestBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"title\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [requestBody appendData:[title dataUsingEncoding:NSUTF8StringEncoding]]; 
     [requestBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    } 


    if (description) { 
     [requestBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [requestBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"description\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [requestBody appendData:[description dataUsingEncoding:NSUTF8StringEncoding]]; 
     [requestBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    } 

    [requestBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] 
      dataUsingEncoding:NSUTF8StringEncoding]]; 

    [request setHTTPBody:requestBody]; 

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
     NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
     if ([responseDictionary valueForKeyPath:@"data.error"]) { 
      if (failureBlock) { 
       if (!error) { 

        error = [NSError errorWithDomain:@"imguruploader" code:10000 userInfo:@{NSLocalizedFailureReasonErrorKey : [responseDictionary valueForKeyPath:@"data.error"]}]; 
       } 
       failureBlock(response, error, [[responseDictionary valueForKey:@"status"] intValue]); 
      } 
     } else { 
      if (completion) { 
       completion([responseDictionary valueForKeyPath:@"data.link"]); 
      } 

     } 

    }]; 
} 

Я полагаю, что причина здесь в том, что я пропустил некоторый дополнительный параметр, но я полностью потерял его. Спасибо заранее.

ответ

1

Наконец изображение загружается, главный причина для публикации не была определена access_token:

[request setValue:[NSString stringWithFormat:@"Bearer %@", token] forHTTPHeaderField:@"Authorization"]; 

и удаление словаря с партией аметров, в случае почтовых запросов на Imgur - нет необходимости.

  • (аннулируются) uploadPhoto: (NSData *) ImageData название: (NSString *) Название Описание: (NSString *) Описание access_token: (NSString *) лексема тема: (NSString *) тема completeBlock: (void (^) (результат NSString *)) завершение failureBlock: (void (^) (ответ NSURLResponse *, ошибка NSError *, состояние NSInteger)) failureBlock { NSAssert (imageData, @ "Данные изображения необходимы");

    NSString *urlString = @"https://api.imgur.com/3/image.json"; 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ; 
    
    [request setValue:[NSString stringWithFormat:@"Bearer %@", token] forHTTPHeaderField:@"Authorization"]; 
    
    [request setURL:[NSURL URLWithString:urlString]]; 
    
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; 
    
    [request setTimeoutInterval:30]; 
    [request setHTTPMethod:@"POST"]; 
    
    NSMutableData *body = [[NSMutableData alloc] init]; 
    
    NSString *boundary = @"---------------------------0983745982375409872438752038475287"; 
    
    
    
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; 
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"]; 
    

    данные вида; имя = \ "% @ \" \ г \ п \ г \ п», парам] dataUsingEncoding: NSUTF8StringEncoding]];

    if (imageData) { 
    
    
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
        [body appendData:[@"Content-Disposition: attachment; name=\"image\"; filename=\".tiff\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    
        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
        [body appendData:[NSData dataWithData:imageData]]; 
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    
    } 
        if (title) { 
         [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
         [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"title\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
         [body appendData:[title dataUsingEncoding:NSUTF8StringEncoding]]; 
         [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
        } 
    
    
        if (description) { 
         [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
         [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"description\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
         [body appendData:[description dataUsingEncoding:NSUTF8StringEncoding]]; 
         [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
        } 
    
    
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    
    
    [request setHTTPBody:body]; 
    
    
    
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
        NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
        if ([responseDictionary valueForKeyPath:@"data.error"]) { 
         if (failureBlock) { 
          if (!error) { 
    
           error = [NSError errorWithDomain:@"imguruploader" code:10000 userInfo:@{NSLocalizedFailureReasonErrorKey : [responseDictionary valueForKeyPath:@"data.error"]}]; 
          } 
          failureBlock(response, error, [[responseDictionary valueForKey:@"status"] intValue]); 
         } 
        } else { 
         if (completion) { 
          completion([responseDictionary valueForKeyPath:@"data.link"]); 
         } 
    
        } 
    
    }]; 
    

    }

2

Глядя на https://api.imgur.com/endpoints/image вы видите, что вам нужно выполнить запись со следующими параметрами (см: ios Upload Image and Text using HTTP POST):

Я думаю, вам не хватает _params[@"type"] = @"base64";

// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept. 
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init]; 
_params[@"type"] = @"base64"; 
_params[@"name"] = @"myImage"; 

// the boundary string : a random string, that will not repeat in post data, to separate post data fields. 
NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"]; 

// create request 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];          
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; 
[request setHTTPShouldHandleCookies:NO]; 
[request setTimeoutInterval:30]; 
[request setHTTPMethod:@"POST"]; 

// set Content-Type in HTTP header 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant]; 
[request setValue:contentType forHTTPHeaderField: @"Content-Type"]; 

// post body 
NSMutableData *body = [NSMutableData data]; 

// add params (all params are strings) 
for (NSString *param in _params) { 
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; 
} 

// add image data 
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0); 
if (imageData) { 
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:imageData]; 
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
} 

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 

// setting the body of the post to the reqeust 
[request setHTTPBody:body]; 

// set the content-length 
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

// set URL 
[request setURL:requestURL]; 
+0

Спасибо, но, к сожалению, она не работает причина ... отличается от ... – Melany

+0

, который отвечает? – ppaulojr

+0

Я получаю следующую ошибку: Ошибка Домен = NSURLErrorDomain Code = -1012 "(null)" UserInfo = {NSErrorFailingURLStringKey = https: //api.imgur.com/3/upload, NSUnderlyingError = 0x7fd56618eda0 {Ошибка домена = kCFErrorDomainCFNetwork Code = -1012 "(null)" UserInfo = {_ kCFURLErrorAuthFailedResponseKey = {url = https://api.imgur.com/3/upload}} }, NSErrorFa ilingURLKey = https: //api.imgur.com/3/upload} – Melany

 Смежные вопросы

  • Нет связанных вопросов^_^