Friday 13 January 2017

How To send Sms using Server side Swift .



In this example I am going to use Perfect.org as  Swift sider Server .

You can use IMB's product or other  to achieve this task  ,as  Swift is now open source language  .

If you see Twilio Docs ,  They only provide  server sider   SDKs for C#, Java, Ruby, Node.js, Python languages: 

And if you send message from Twilio Dashboard You will see Code for  cURL  , C#, Java, Ruby, Node.js, Python 








 At this Time Twilio not provide  any library for Swift .  so only way to achieve this task is by cURL's commands

Native Command of cURL is


         --data-urlencode 'To=+YourPhoneNumber'  \
         --data-urlencode 'From=+TwilioProvidePhoneNumber'  \
         --data-urlencode 'Body= Message sent  to Server '  \
         -u 'YourLiveSID :YourLiveToken'




To convert native Curl commands to Perfect Wrapper . 



swift --version
Apple Swift version 3.0.1 (swiftlang-800.0.58.6 clang-800.0.42.1)
Target: x86_64-apple-macosx10.9




 Swift  server side code (Perfect.org  using cURL ) 


   let curl = CURL()

        let _ = curl.setOption(CURLOPT_URL, s: "https://api.twilio.com/2010-04-01/Accounts/MyLiveSID33323232/Messages.json")
        
        let _ = curl.setOption(CURLOPT_POST, int: 1)
      
        let _ = curl.setOption(CURLOPT_USERPWD, s: “MyLiveSID33323232:MyLivetoken ")

          let fields = ["From":"+56456456”,
"To":"+MyVerifiedPhoneNumber56465456456”,
"Body":" Message sent  from swift Serve"]
        
    
        let str = fields.map { $0.key + "=" + ($0.value.stringByEncodingURL) }
            .reduce("") { $0.isEmpty ? $1 : $0 + "&" + $1}
        
        let byteArray = [UInt8](str.utf8)

        curl.setOption(CURLOPT_POSTFIELDSIZE, int: byteArray.count)
        
        curl.setOption(CURLOPT_COPYPOSTFIELDS, v: UnsafeMutablePointer(mutating: byteArray))
        
        let _ = curl.setOption(CURLOPT_VERBOSE, int: 1)
        
        let r = curl.performFully()
        
        print(r.0)



Enjoy Server Sider Swift :-) 


If this not work Please notify me to update this ...





No comments:

Post a Comment