2012-04-19 196 views
3

我怎麼能send SMS through twilio,我已經嘗試過,並做了以下。在ios上通過Twilio發送短信?

- (IBAction)sendButtonPressed:(id)sender 
{ 
    NSLog(@"Sending request."); 

    // Common constants 
    NSString *kTwilioSID = delegate.sessionId; 
    NSString *kTwilioSecret = delegate.twilioToken; 
    NSString *kFromNumber = delegate.twlioNumber; 
    NSString *kToNumber = @"+14126620408"; 
    NSString *kMessage = @"Hi there......"; 

    // Build request 
    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"]; 

    // Set up the body 
    NSString *bodyString = [NSString stringWithFormat:@"From=%@&To=%@&Body=%@", kFromNumber, kToNumber, kMessage]; 
    NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; 
    [request setHTTPBody:data]; 
    NSError *error; 
    NSURLResponse *response; 
    NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

    // Handle the received data 
    if (error) { 
     NSLog(@"Error: %@", error); 
    } else { 
     NSString *receivedString = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding]; 
     NSLog(@"Request sent. %@", receivedString); 
    }  
} 

並且出現錯誤:操作無法完成。 (kCFErrorDomainCFNetwork錯誤-1012。 請幫忙做這個問題,或與我分享任何幫助材質。在此先感謝。

+0

我使用您的代碼在iOS應用程序中發送短信。但是,在發送短信時,我收到了與您不同的錯誤。 '收件人'號碼+91 **********不是有效的電話號碼(代碼21211) 我檢查了我使用的號碼是否正確定義了+(國家代碼)(電話號碼沒有)。你能幫我解決這個問題嗎? – Rachit 2013-08-20 12:17:15

+0

嗨你解決了這個問題嗎? – 2014-09-29 10:40:33

回答

4

this answer,錯誤1012意味着身份驗證的請求被用戶取消。

這只是一種預感,但您可能想嘗試使用HTTP基本身份驗證,方法是添加一個Authorization標頭,如下所示:Objective-c HTTP Basic authentication,而不是將URL包含在URL字符串中,該字符串依靠Objective C庫將它們正確地轉換爲標頭。

4

確保HttpPost參數是URL編碼的,所以你應該改變

NSString *kToNumber = @"+14126620408"; 

NSString *kToNumber = @"%2B14126620408"; 
0

我寫這篇博客文章,以幫助您快速使用Xcode中8完成,斯威夫特3

https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html

使用服務器端您選擇的語言和HTTP請求的Alamofire,請求歸結爲:

@IBAction func sendData(sender: AnyObject) { 
    let headers = [ 
     "Content-Type": "application/x-www-form-urlencoded" 
    ] 

    let parameters: Parameters = [ 
     "To": phoneNumberField.text ?? "", 
     "Body": messageField.text ?? "" 
    ] 

    Alamofire.request("YOUR_NGROK_URL/sms", method: .post, parameters: parameters, headers: headers).response { response in 
      print(response) 

    } 
}