TaCode Tuesdays: How to Build an iOS Chat Application using Swift (Part 3)

Posted by Alex Misevski on October 11, 2016

TaCode_Image_Week_8.jpg

Welcome back to TaCode Tuesdays! This is the only place you can find snippets of code for use in your very own text/voice apps, along with a weekly dose of taco puns. I’m a developer here at Zang and not only am I a big fan of tacos (if that wasn’t already apparent), I’m also a fan of open source. My goal is to share a new app idea each week that you're free to use “as is” or modify and use as the basis for your next app.

The past two weeks, I've been detailing how you can create a chat application using Swift and Zang on iOS—you can check out PART 1 here and PART 2 here, and as always, if you’d like to learn how to get started on Zang, take a look at our very first post.

This week I’m going to continue the series by walking through the final 3 steps. I would recommend that you read the first post in the series, then the second post before reading this blog, otherwise it won't make any sense! 

The following steps show how to create the voice call feature of your iOS chat app after completing the IP messaging feature (detailed in the previous two posts). This has three easy steps: (1) Authenticate your account in Zang; (2) Create a JSON string to initiate Zang’s call API; and (3) Initiating the voice call using Step 2. Anyways, let's get right into the final steps.

Step 1: Authenticate your Zang request via the method https://{AccountSid}:{AuthToken}@api.zang.io/

if let url = NSURL(string: "https://{AccountSid}:{AuthToken}@api.zang.io/") //Account SID and AuthToken are found on your Zang dashboard

{
   let request = NSMutableURLRequest(URL: url)
   request.HTTPMethod = "POST" //Or GET if that's what you need
   //This is where you add your HTTP headers like Content-Type, Accept and so on
   request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")  //This is where you add your HTTP headers like Content-Type, Accept and so on
  let session = NSURLSession.sharedSession()
   session.dataTaskWithRequest(request, completionHandler: { (returnData, response, error) -> Void in
       var strData = NSString(data: returnData, encoding: NSUTF8StringEncoding)
       println("\(strData)")
   }).resume() //Remember this one or nothing will happen :-)
}
 

Step 2: Create a JSON string according to the following fields specified by Zang.  Below is an example JSON for making a call as POST request:

{
   "To": "############@sip.zang.io",
   "From": "############",
   "Url": "{The URL requested once the call connects....",
   "Method": POST,
   "FallbackUrl": ,
   "FallBackMethod":,
   "StatusCallback":,
   "StatusCallbackMethod":,
   "HeartbeatUrl":,
   "HeartbeatMethod":,
   "ForwardedFrom":,
   "PlayDtmf":,
   "Timeout":,
   "Record":,
   "RecordCallback":,
   "RecordCallbackMethod":,
   "Transcribe":,
   "TranscribeCallback":,
   "StraightToVoicemail":,
   "IfMachineUrl":,
   "IfMachineMethod":,
   "SipAuthUsername":,
   "SipAuthPassword":
}
 

Step 3: Make a voice call using the Zang.io REST API with the JSON string above for the parameter named "params" to invoke the call request. Below is a code snippet example for making a simple call request:

private func clientURLRequest(path: String, params: Dictionary<String, AnyObject>? = nil) -> NSMutableURLRequest {
   let request = NSMutableURLRequest(URL: NSURL(string: "http://api.zang.io/"+path)!)
   if let params = params {
       var paramString = ""
       for (key, value) in params {
           let escapedKey = key.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())
           let escapedValue = value.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())
           paramString += "\(escapedKey)=\(escapedValue)&"
       }
       request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
       request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
   }
   if let token = token {
       request.addValue("Bearer "+token, forHTTPHeaderField: "Authorization")
   }
   return request
}
 

Summing it Up

Developing chat applications using Swift with IP messaging, voice call, and conference features can be implemented using Node.js’ open source library and Zang. Node.js will allow you to freely use an IP messaging capability as part of its built-in features without having to pay for one. Utilizing Zang’s call API to create app-to-app, app-to-phone, and phone-to-phone voice calls is a premium feature and gives your iOS chat app more value, even outside internet connectivity. When using Swift, developers have more flexibility. This flexibility is due, in part, to the technology’s compatibility with a lot of good open source libraries, the pure convenience of using less lines of code than iOS’ native counterpart, and better performance through its optimized framework.

Well, that’s it for now! If you have any thoughts about the app or just want to share your own taco-related thoughts, you can comment below. If you want a reminder, sign up to get notifications of new blog posts. I'll be back in 2 weeks with another installment of TaCode Tuesdays...after this 3-parter I really need a break!

Topics: Communication Apps, Ideas, TaCode Tuesday, cPaaS

IMAGINE IT. BUILD IT.

Communicate better. 

Cloud communication technology that transforms your conversations — and your business.

 

Subscribe to Email Updates