现在希望在ios上完成这样一个任务:把一副图片以stream的形式发出post request到一个API,返回json数据并解析。第一步是需要在ios中进行http请求。
网上总结了5种 Swift中的HTTP请求:http://swiftist.org/topics/135
尝试其中swiftHTTP框架和Obj-c的AFnetworking库,由于我没有开发者账号,在使用的xcode7 beta版是swift2,与引入的SwiftHTTP.framework有很多语法不兼容, 最终选择AFNetworking。
引入AFNetworking framework方法比较简单,可以直接参照Github上的说明。
+(void) uploadImage:(UIImage *)image {
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSString* path = @"https://api.projectoxford.ai/face/v0/detections";
NSArray* array = @[@"entities=true",
@"analyzesFaceLandmarks=true",
@"analyzesAge=false",
@"analyzesGender=false",
@"analyzesHeadPose=true",
];
NSString* string = [array componentsJoinedByString:@"&"];
path = [path stringByAppendingFormat:@"?%@", string];
NSURL *url = [NSURL URLWithString:path ];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:imageData];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
[request setValue:OxfordKey forHTTPHeaderField:@"Ocp-Apim-Subscription-Key"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,id result) {
NSLog(@"Success:***** %@", result);
NSDictionary *JSON = (NSDictionary *)result;
NSString *s_pitch = [[[JSON valueForKey:@"attributes"]valueForKey:@"headPose"]valueForKey:@"pitch"];
NSString *s_roll = [[[JSON valueForKey:@"attributes"]valueForKey:@"headPose"]valueForKey:@"roll"];
NSString *s_yaw = [[[result valueForKey:@"attributes"]valueForKey:@"headPose"]valueForKey:@"yaw"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@ ***** %@", operation.responseString, error);
}];
[operation start];
}
参考文献
本文介绍了如何在iOS应用中通过Swift实现HTTP请求,特别是将图片作为stream发送POST请求到API,并解析返回的JSON数据。在尝试了SwiftHTTP和AFNetworking后,由于Swift版本不兼容问题,选择了AFNetworking库,并详细说明了如何在Xcode中引入和使用AFNetworking Framework。

1831

被折叠的 条评论
为什么被折叠?



