3

我正在尝试将消息与图表文件一起发送,但无济于事。此代码适用于发送常规消息。我正在使用 AFNetworking 来执行此操作。我使用的 stocktwits 端点:

https://api.stocktwits.com/api/2/messages/create.json

NSURL *url = [NSURL fileURLWithPath:chartFilePath];
NSDictionary *params = @{@"in_reply_to_message_id": inReplyToMsgId, @"chart":url, @"body":msg, @"access_token":oauthtoken};

NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"POST" URLString:reqURL parameters:params];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setResponseSerializer:[AFHTTPResponseSerializer alloc]];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{

    NSString *json_string = [[NSString alloc] initWithData:responseObject 
    encoding:NSUTF8StringEncoding];

    NSLog(@"stocktwits: %@", json_string);     
}failure:^(AFHTTPRequestOperation *operation, NSError *error){

     NSLog(@"Failure: %@", error);
     failure(error);
}];
[manager.operationQueue addOperation:operation];

我得到的错误信息:

 stocktwits: {"response":{"status":422},"errors":[{"message":"We couldn't recognize the image format. Format must be one of: image/jpeg image/pjpeg image/png image/x-png image/gif"}]}

我一直在玩 AFNetworking 提供的其他解决方案,例如 AFMultipartFormData,但也无济于事。

有人知道我在这里想念什么吗?

谢谢!!!

4

1 回答 1

0

我可以使用此代码上传一张图表/图像,API 的限制:-

- (void) commonPostWithPath:(NSString*)path params:(NSDictionary*)parameters image:(UIImage*_Nullable)image completion:(MOTwitterCompletionBlock _Nullable ) completion{
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:StockTwits_BaseURL]];
    [manager POST:path parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (image) {
            [formData appendPartWithFileData:UIImagePNGRepresentation(image) name:@"chart" fileName:@"Stocks Live" mimeType:@"image/png"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (completion) completion(responseObject, nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completion(nil, error);
    }];
}
于 2021-03-30T16:51:55.467 回答