Detect the Language of Text in Swift

Cloudmersive
1 min readJul 15, 2021

--

Looking to improve the international experience of your online platforms? If so, a good place to start is integrating language identification and translation tools into your system. In today’s tutorial, we will be demonstrating how you can use a Natural Language Processing API in Swift to automatically determine which language a text string is written in.

To call the NLP function, simply input the text string into the following code:

import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
var semaphore = DispatchSemaphore (value: 0)let parameters = "textToDetect=%3Cstring%3E"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://api.cloudmersive.com/nlp-v2/language/detect")!,timeoutInterval: Double.infinity)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("YOUR-API-KEY-HERE", forHTTPHeaderField: "Apikey")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}
task.resume()
semaphore.wait()

If you need to retrieve an API key, you can do so by visiting the Cloudmersive website and registering for a free account; this provides 800 calls/month across our multitude of APIs.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.