WordPress XML-RPC 框架
WordPress XML-RPC 库是一个轻量级的 XML-RPC 客户端,适用于 iOS 和 OS X。
它是基于 Eric Czarny 的 Cocoa XML-RPC 框架,但去掉了所有的网络代码,并添加了我们的一些功能。
安装
WordPress XML-RPC 使用 CocoaPods 简化依赖管理。
只需将此代码添加到 Podfile 中,然后运行 pod install
。
pod 'wpxmlrpc'
如果不使用 CocoaPods,另一种选择是将 WPXMLRPC
文件夹复制到您的项目中。
使用方法
WordPress XML-RPC 只提供编码和解码 XML-RPC 的类。您可以自由使用您喜欢的网络库。
构建 XML-RPC 请求
NSURL *URL = [NSURL URLWithString:@"http://example.com/xmlrpc"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
[request setHTTPMethod:@"POST"];
WPXMLRPCEncoder *encoder = [[WPXMLRPCEncoder alloc] initWithMethod:@"demo.addTwoNumbers" andParameters:@[@1, @2]];
[request setHTTPBody:[encoder dataEncodedWithError:nil]];
使用流构建 XML-RPC 请求
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *directory = [paths objectAtIndex:0];
NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *streamingCacheFilePath = [directory stringByAppendingPathComponent:guid];
NSURL *URL = [NSURL URLWithString:@"http://example.com/xmlrpc"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
[request setHTTPMethod:@"POST"];
NSInputStream *fileStream = [NSInputStream inputStreamWithFileAtPath:filePath];
WPXMLRPCEncoder *encoder = [[WPXMLRPCEncoder alloc] initWithMethod:@"test.uploadFile" andParameters:@[fileStream]];
[encoder encodeToFile:streamingCacheFilePath error:nil];
NSError *error = nil;
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
unsigned long contentLength = [[attributes objectForKey:NSFileSize] unsignedIntegerValue];
NSInputStream * inputStream = [NSInputStream inputStreamWithFileAtPath:filePath];
[request setHTTPBodyStream:inputStream];
[request setValue:[NSString stringWithFormat:@"%lu", contentLength] forHTTPHeaderField:@"Content-Length"];
解析 XML-RPC 响应
NSData *responseData = …
WPXMLRPCDecoder *decoder = [[WPXMLRPCDecoder alloc] initWithData:responseData];
if ([decoder isFault]) {
NSLog(@"XML-RPC error %@: %@", [decoder faultCode], [decoder faultString]);
} else {
NSLog(@"XML-RPC response: %@", [decoder object]);
}
致谢
The Base64 encoder/decoder found in NSData+Base64 is created by Matt Gallagher.
The original Cocoa XML-RPC Framework was developed by Eric Czarny and now lives at github.com/corristo/xmlrpc