How to make Twilio api Post request with the help

2019-07-11 06:14发布

问题:

I want to access Twilio api using AFNetworking. I tried number of ways but not get success. Please help me, if anyone did Tiwilo post request using AFNetworking.

Case 1: This is my native objective-c working code.

NSString *urlString = [NSString stringWithFormat:@"https://%@:%@@api.twilio.com/2010-04-01/Accounts/%@/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID];

NSURL *url                      = [NSURL URLWithString:urlString];
NSMutableURLRequest *request    = [[NSMutableURLRequest alloc] init];

[request setURL:url];
[request setHTTPMethod:@"POST"];

NSString *bodyString    = [NSString stringWithFormat:@"From=%@&To=%@&Body=%@", from, to, message];

NSData *data            = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    if (connectionError)
    {
        DLog(@"Error: %@", connectionError);

        completionBlock(connectionError, NO);
    }
    else
    {
        completionBlock(connectionError, YES);
    }
}];

Case 2: Using AFNetorking: Code that is not working:

Code:

    NSString *urlString = [NSString stringWithFormat:@"https://%@:%@@api.twilio.com/2010-04-01/Accounts/%@/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID];

NSDictionary *dict = @{
                       @"From" : from,
                       @"To" : to,
                       @"Body" : message
                       };


AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager POST:urlString parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject)
 {
     NSLog(@"Success: %@", responseObject);
 }
      failure:
 ^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"Error: %@", error);
 }];

Related Error:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x1775e660 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set., NSUnderlyingError=0x175101b0 "Request failed: bad request (400)"}

Case 3: Using AFNetorking: Another Code that is also not working:

Code:

 NSString *urlString = [NSString stringWithFormat:@"https://%@:%@@api.twilio.com/2010-04-01/Accounts/%@/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID];
NSURL *url                      = [NSURL URLWithString:urlString];
NSMutableURLRequest *request    = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];

NSString *bodyString    = [NSString stringWithFormat:@"From=%@&To=%@&Body=%@", from, to, message];
NSData *data            = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"error: %@", error);
}];

[operation start];

Related Error:

 Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x177a3e70 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

Thank you.

回答1:

Ricky from Twilio here. First off a quick disclaimer. Making a request to Twilio directly from an iOS app requires you to embed your Twilio account credentials in the app, which is dangerous. My recommendation would be to send the SMS from a server side script that your app makes a request to in order to keep your credentials safe.

That being said, your code is really close. By default, Twilio's REST API returns XML. If you want to parse the response as it's returned by default you can update the code in version 2 to use the AFXMLParserResponseSerializer:

operation.responseSerializer = [AFXMLParserResponseSerializer serializer];

If you'd rather work with JSON then you update the Twilio URL you're making the POST request to and indicate you'd like a JSON response:

NSString *urlString = [NSString stringWithFormat:@"https://%@:%@@api.twilio.com/2010-04-01/Accounts/%@/SMS/Messages.json", kTwilioSID, kTwilioSecret, kTwilioSID];

Hope that helps.