Using Apple’s Built-in NaturalLanguage Framework For Sentiment Analysis in iOS App Development

Kevin Jonathan
4 min readNov 25, 2022
Photo by Alexander Sinn on Unsplash

Apple has its own built-in framework that we can use in our XCode project called NaturalLanguage. This framework supports sentiment analysis as well so that once we implemented it, it will magically runs and provide the result in our app based on your code.

Wait, What Is Sentiment Analysis?

According to Wikipedia, Sentiment analysis (also known as opinion mining or emotion AI) is the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information.

Simply put, we use AI to detect human emotions to determine whether it’s positive, neutral or negative. Sentiment analysis is widely applied to voice of the customer topics such as reviews, survey responses, and social media.

Is It Hard to Implement Sentiment Analysis in iOS App using NaturalLanguage?

Implementing Apple’s NaturalLanguage for sentiment analysis might be easier than you thought if you already understand the core of its framework and read the documentation while implementing it.

That said, there are several limitations that you have to keep in mind if you want to use this framework:

  1. Limited language support, for sentiment analysis I think it might support fewer languages than the NaturalLanguage itself (you have to test this by yourself to find out if your language can be used)
  2. It’s far from perfect, it probably can’t detect complicated sentence cases like “I do not dislike noodles.” or “Disliking someone is not really my thing.” since these kind of sentences need negative handling.

If you want to develop a far more superior model than the Apple has provided, consider creating your own text classifier model using CreateML framework, and later add it to your own project using CoreML.

Implementation

Finally we have reached this part. For the implementation, I will use SwiftUI to save time and put the layout magically.

First, let’s open our XCode and create a new project using SwiftUI interface and name it “NaturalLanguageProject” or any name that you want. Now we have initiated our project!

NaturalLanguageProject running on XCode version 14.1

Now let’s create our view first so that we can test our app later. We will add a textfield to input our sentence, a button to check the sentence classification, and a text to show the result!

//
// ContentView.swift
// NaturalLanguageProject
//
// Created by Kevin Jonathan on 25/11/22.
//

import SwiftUI

struct ContentView: View {
@State var sentence: String = ""
@State var emotion: String = ""

var body: some View {
VStack(spacing: 8) {
TextField("Type sentence..", text: $sentence)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 8)
.strokeBorder(.blue)
)
.padding()

Button(
action: {
emotion = "😀"
}, label: {
Text("Detect")
})

Text(emotion)
}
.padding()
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

Wait, where is the NaturalLanguage?

We haven’t done yet. Now let’s add the utility class for processing the NaturalLanguage. Add new files to your project, select “Swift file” and save it with “NaturalLanguageUtility” name. And let’s add the code to determine the result of sentiment analysis.

//
// NaturalLanguageUtility.swift
// NaturalLanguageProject
//
// Created by Kevin Jonathan on 25/11/22.
//

import Foundation
import NaturalLanguage

struct NaturalLanguageUtility {
static func processSentimentAnalysis(input: String) -> Double {
let tagger = NLTagger(tagSchemes: [.sentimentScore])
tagger.string = input
let sentiment = tagger.tag(at: input.startIndex, unit: .paragraph, scheme: .sentimentScore).0
let score = Double(sentiment?.rawValue ?? "0") ?? 0
return score
}
}

Woah, slow down! What are these codes?

Basically, we have to import “NaturalLanguage”, and initialize a NLTagger instance to classify text using sentiment analysis. The instance took our input as its string, and call the tag function to determine the sentiment analysis result. Tag function finds a tag for a given linguistic unit, for a single scheme (which we use sentimentScore to make it work), at the specified character position.

After that, we can get the rawValue of the sentiment result, and return it as a double. Usually, we can classify the texts as positive (if the value ranges in 0 < value ≤ 1), neutral or can’t be determine (if the value is 0), and negative (if the value ranges in -1 ≤ value < 0).

Final touch

Now, let’s call this function on our app UI, and get the result for every sentence that we have inputted.

                ...
.padding()

Button(
action: {
determineEmotion()
}, label: {
Text("Detect")
})

Text(emotion)
}
.padding()
}
}

extension ContentView {
private func determineEmotion() {
guard !sentence.isEmpty else {
emotion = ""
return
}

let score = NaturalLanguageUtility.processSentimentAnalysis(input: sentence)

switch score {
case let value where value > 0:
emotion = "😀"
case let value where value < 0:
emotion = "🙁"
default:
emotion = "😐"
}
}
}

struct ContentView_Previews: PreviewProvider {
..

In the UI section, I added an extension of ContentView, and add a determineEmotion function to get the sentence value, the sentiment analysis result, and to assign the emotion value. Pretty straightforward, isn’t it?

And here is the result when we run our code (I run this directly on SwiftUI preview):

The result when we run our code (SwiftUI Preview)

Looks pretty neat, right? You can continue to develop the app as you wish by tweaking the UI or adding more functions to NaturalLanguageUtility class! You can also improve or change the code implementation!

That’s what I know about implementing NaturalLanguage for sentiment analysis in iOS apps. Thank you for reading my article!

P.S: Please let me know if I said something wrong.

--

--

Kevin Jonathan

Just a student intricately weaving personal narratives and technology related stuffs, currently navigating the intersections of life.