To generate QR code in iOS device, I'm using this library.

From the their GitHub repo, already got the instruction. Here I want to point out 2 things:

1. Assign to UIImage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
NSString *text = @"The text to encode";
NSError *error = nil;
ZXMultiFormatWriter *writer = [ZXMultiFormatWriter writer];
ZXBitMatrix* result = [writer encode:text
format:kBarcodeFormatQRCode
width:500
height:500
error:&error];
if (result) {
CGImageRef image = [[ZXImage imageWithMatrix:result] cgimage];

// LOOK AT HERE, this line will crash
imageView.image = [[UIImage alloc] initWithCGImage:image];
} else {
NSLog(@"QR code encode error %@", [error localizedDescription]);
}

See the code above, it will crash when convert CGImageRef to UIImage. So change to

1
2
UIImage *image = [[UIImage alloc] initWithCGImage:[[ZXImage imageWithMatrix:result] cgimage]];
imageView.image = image;

It works now. This is something to do with ARC, checkout this for more info

2. It has margin

QR code with margin

You can see the margin took out some space. To remove the margin

1
2
3
4
5
6
7
8
9
10
11
12
13
...

// ADD THIS 2 LINES
ZXEncodeHints *hints = [ZXEncodeHints hints];
hints.margin = @0;

ZXBitMatrix* result = [writer encode:text
format:kBarcodeFormatQRCode
width:500
height:500
hints:hints // ADD THIS LINE
error:&error];
...

Run it again, now it utilise the whole image.

QR code without margin

References: