iOSアプリから、バーコード(code39)を生成させる必要があったのでメモ。
iOS9のAVFoundationでは、code128を生成させることはできるが、code39はできない?ようなので、自前で実装しようとしたが、便利なライブラリ(RSBarcodes_Swift)があったのでそれを使う。
※CocoaPodsインストール済み前提
1.XCodeでSwiftプロジェクト作成する
2.Podfile作成、インストール
~ pod init
use_frameworks!
pod 'RSBarcodes_Swift', '~> 0.1.5'
~ pod install
3.
~ cd プロジェクトルートパス
~ git submodule add https://github.com/yeahdongcn/RSBarcodes_Swift.git
4..xcworkspaceファイルからプロジェクトを開く
5.RSBarcodes_Swiftフォルダの中の、RSBarcodes.xcodeprojを自分で作ったプロジェクトにドラッグして追加する

7.ViewController.swift編集
import UIKit
import AVFoundation
import RSBarcodes
class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
let type = [
AVMetadataObjectTypeCode39Code,
AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeCode93Code,
AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypeUPCECode,
AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeITF14Code,
AVMetadataObjectTypeInterleaved2of5Code,
AVMetadataObjectTypeDataMatrixCode,
AVMetadataObjectTypeQRCode,
// AVMetadataObjectTypeAztecCode,
AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeFace,
AVMetadataObjectTypePDF417Code,
]
let s = "ABCDE12345"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let lbl: UILabel = UILabel(frame: CGRectMake(0, 0, 400, 50))
lbl.text = "generate code: \(s)"
lbl.layer.position = CGPoint(x: 200, y: 40)
self.view.addSubview(lbl)
// ImageView生成
let cnt = type.count
var img: [UIImageView] = Array<UIImageView>(count: cnt + 1, repeatedValue: UIImageView())
var y: CGFloat = 100
for var i = 0; i < cnt + 1; i++ {
let width = CGFloat(300)
let height = CGFloat(100)
img[i] = UIImageView(frame: CGRectMake(0, 0, width, height))
y += CGFloat(i % 2) * height
img[i].layer.position = CGPoint(x: width / 2 + (width * CGFloat(i % 2)), y: y)
view.addSubview(img[i])
}
// AVFoundation code128しか生成できない?
let data = s.dataUsingEncoding(NSASCIIStringEncoding)
let filter = CIFilter(name: "CICode128BarcodeGenerator")
filter!.setValue(data, forKey: "inputMessage")
img[0].image = UIImage(CIImage: filter!.outputImage!)
// RSBarcodes
let gen = RSUnifiedCodeGenerator.shared
gen.fillColor = UIColor.whiteColor()
gen.strokeColor = UIColor.blackColor()
for var i = 0; i < cnt - 1; i++ {
if let _img = gen.generateCode(s, machineReadableCodeObjectType: type[i]) {
print("\(i) \(type[i])")
// img[i].image = RSAbstractCodeGenerator.resizeImage(_img, scale: 1.0)
img[i + 1].image = _img
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
iPad Retinaシミュレータで表示した結果
(表示出来ていない種類もあるが、code39は表示されているので一応OKとしておきます)


