Skip to content

Instantly share code, notes, and snippets.

@shortstuffsushi
Last active November 19, 2019 05:58
Show Gist options
  • Save shortstuffsushi/e0a0252e70a6f42b1049 to your computer and use it in GitHub Desktop.
Save shortstuffsushi/e0a0252e70a6f42b1049 to your computer and use it in GitHub Desktop.
iOS WiFi Print
//
// Printer.h
// Print
//
// Created by Graham Mueller on 10/27/15.
// Copyright © 2015 Graham Mueller. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef void (^GenericErrorCallback)(NSString *err)
@interface Printer : NSObject
- (id)initWithIPAddress:(NSString *)ipAddress port:(UInt32)port;
- (void)sendDataToPrinter:(NSData *)data callback:(GenericErrorCallback)callback;
@end
//
// Printer.m
// Print
//
// Created by Graham Mueller on 10/27/15.
// Copyright © 2015 Graham Mueller. All rights reserved.
//
#import "Printer.h"
@interface Printer () <NSStreamDelegate>
@property (strong, nonatomic) NSString *ipAddress;
@property (assign, nonatomic) UInt32 port;
@property (strong, nonatomic) NSOutputStream *outputStream;
@property (strong, nonatomic) NSData *documentData;
@property (copy, nonatomic) GenericErrorCallback callback;
@end
@implementation Printer
- (id)initWithIPAddress:(NSString *)ipAddress port:(UInt32)port {
if (self = [super init]) {
_ipAddress = ipAddress;
_port = port;
}
return self;
}
- (void)sendDataToPrinter:(NSData *)data callback:(GenericErrorCallback)callback {
self.callback = callback;
self.documentData = data;
// Open socket. Note that we're entirely ignoring the Input Stream.
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)self.ipAddress, self.port, NULL, &writeStream);
self.outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[self.outputStream setDelegate:self];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream open];
}
#pragma mark - Stream Delegate methods
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event {
switch (event) {
// Stream is ready for writing, send the print data
case NSStreamEventHasSpaceAvailable:
[self.outputStream write:self.documentData.bytes maxLength:self.documentData.length];
self.callback(nil);
[self.outputStream close];
break;
// Something error happen, let the user know
case NSStreamEventErrorOccurred:
self.callback([[self.outputStream streamError] localizedDescription]);
[self.outputStream close];
break;
default: break;
}
}
@end
@shortstuffsushi
Copy link
Author

This is the most direct and simple printing method via WiFi. It's by no means bullet proof, but it's enough to get something coming out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment