LoginSignup
10
11

More than 5 years have passed since last update.

SwiftでAPIを取得する(感情解析)

Last updated at Posted at 2016-10-09

環境

  • Swift2.0
  • Xcode7.3.1

API

使用したのはMetadata社が提供する『Mextractr 感情解析API』です。登録して使いました。お好きなサイトから取ってきてください。

コード

get.swift
import UIKit

class AnalyzeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let str = "私は嬉しい"
        let encodedString = str.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
            getAPI(encodedString!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func getAPI(encordedstr:String) {

        let URL = NSURL(string: "http://ap.mextractr.net/ma9/emotion_analyzer?out=json&apikey=<APIキー>&text=\(encordedstr)")
        let req = NSURLRequest(URL: URL!)

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config, delegate:nil, delegateQueue:NSOperationQueue.mainQueue())

        let task = session.dataTaskWithRequest(req, completionHandler: {
            (data, response, error) -> Void in
            do {
               //やりたいことを書く
                let dict = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary

                print(dict)

            } catch {
                //エラー処理
            }

        })
        task.resume()
    }
}

こんな感じでgetJsonのメソッドでAPIを叩いてます。呼び出すときは

getAPI(<文字列の名前>)

とかで読んでください。
文字列は、エンコードします。

APIを叩いた結果

{
    "analyzed_text" = "%E7%A7%81%E3%81%AF%E3%80%90%E3%80%90%E5%AC%89%E3%81%97%E3%81%84%E3%80%91%20[2.00,2.00,0.00]%20%20%E3%80%91";
    angerfear = 0;
    joysad = 2;
    likedislike = 2;
}

analyzed_textは、解析した文字列です。デコードすると元に戻ります。
今回は、「私は嬉しい」なので、ポジティブな配点になっています。
いい感じにできました!!

☆★☆★まとめ★☆★☆

APIは叩けると楽しい!

10
11
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11