我有一个完全在android和浏览器上运行的soap webservice,但是当我们将该webservice集成到ios中时,它返回状态代码200但没有返回数据,因此它与一些webservice或一些ios故障有关,
这是代码:
#import "ServerAPI.h"
#import "SharedObjects.h"
#import "TouchXML.h"
@implementation ServerAPI
@synthesize engine;
@synthesize receivedData;
+ (ServerAPI *)api;
{
static ServerAPI *api;
if (nil != api)
return api;
static dispatch_once_t pred;
dispatch_once(&pred, ^{
api = [[ServerAPI alloc] init];
});
return api;
}
- (id)init
{
self = [super init];
if (self) {
engine = [[MKNetworkEngine alloc] initWithHostName:kServerHOST customHeaderFields:nil];
}
return self;
}
- (NSString*)scriptPathForAction:(kActionType)type {
switch (type) {
case kActionTypeGetListing:
return @"GetListing";
case kActionTypeGetListings:
return @"GetListings";
case kActionTypeGetMoreListings:
return @"GetMoreListings";
case kActionTypeLike:
return @"Like";
case kActionTypeMarkExpired:
return @"MarkExpired";
case kActionTypeMarkSpam:
return @"MarkSpam";
case kActionTypeUnLike:
return @"UnLike";
case kActionTypeUploadFile:
return @"UploadFile";
case kActionTypeAddComment:
return @"Comment";
case kActionTypeDeleteComment:
return @"DeleteComment";
case kActionTypeAddListing:
return @"AddListing";
case kActionTypeCheckIfListingExist:
return @"CheckIfListingExist";
case kActionTypeAddUser:
return @"AddUser";
}
}
- (void)executeAction:(kActionType)type withParams:(NSDictionary*)params onCompletion:(APIResponseBlock)completionBlock onError:(APIErrorBlock)errorBlock onValidationError:(APIErrorValidationBlock)validationErrorBlock {
if (apiResponseBlock) {
[apiResponseBlock release];
apiResponseBlock = nil;
}
if (apiErrorBlock) {
[apiErrorBlock release];
apiErrorBlock = nil;
}
apiResponseBlock = [completionBlock copy];
apiErrorBlock = [errorBlock copy];
NSString *XMLNameSpace = kServerNameSpace;
NSString *XMLURLAddress = [kServerHOST stringByAppendingPathComponent:kServerPATH];
NSString *MethodName = [self scriptPathForAction:type];
NSMutableDictionary *postValues = [NSMutableDictionary dictionary];
[postValues addEntriesFromDictionary:params];
postValues[@"hashvalue"] = kServerAPIHash;
progressView = nil;
if ([postValues objectForKey:@"increment"]) {
type = kActionTypeGetListings;
}
if (type == kActionTypeAddListing) {
PoiItem *p = params[@"newPoi"];
postValues[@"title"] = p.name;
postValues[@"description"] = p.name;
postValues[@"address"] = p.address;
postValues[@"price"] = p.price;
postValues[@"discount"] = p.discount;
postValues[@"website"] = p.website;
postValues[@"phone"] = p.phone;
postValues[@"opening_hours"] = p.opening_hours;
postValues[@"entry_cost"] = p.entry_cost;
NSString *lat = [NSString stringWithFormat:@"%f",p.location.latitude];
NSString *lon = [NSString stringWithFormat:@"%f",p.location.longitude];
postValues[@"longitude"] = lon;
postValues[@"latitude"] = lat;
[[SharedObjects objects].df setDateFormat:@"yyyy-MM-dd"];
if (!p.dateFrom)
postValues[@"start_date"] = @"";
else
postValues[@"start_date"] = [[SharedObjects objects].df stringFromDate:p.dateFrom];
if (!p.dateUntil)
postValues[@"end_date"] = @"";
else
postValues[@"end_date"] = [[SharedObjects objects].df stringFromDate:p.dateUntil];
[postValues removeObjectForKey:@"newPoi"];
}
if (type == kActionTypeUploadFile) {
progressView = [params[@"progress"] retain];
NSData *attachData = [NSData dataWithContentsOfFile:params[@"filepath"]];
if (attachData) {
postValues[@"f"] = [attachData base64EncodedString];
}
[postValues removeObjectForKey:@"filepath"];
[postValues removeObjectForKey:@"progress"];
}
NSLog(@"post values %@",postValues);
NSMutableString *sRequest = [[NSMutableString alloc] init];
NSString *SOAPActionURL = [NSString stringWithFormat:@"%@%@", XMLNameSpace, MethodName];
//make soap request
[sRequest appendString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"];
[sRequest appendString:@"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"];
[sRequest appendString:@"<soap:Body>"];
[sRequest appendString:[NSString stringWithFormat:@"<%@ xmlns=\"%@\">",MethodName, XMLNameSpace]];
[postValues enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[sRequest appendString:[NSString stringWithFormat:@"<%@>%@</%@>", key, obj, key]];
}];
//close envelope
[sRequest appendString:[NSString stringWithFormat:@"</%@>", MethodName]];
[sRequest appendString:@"</soap:Body>"];
[sRequest appendString:@"</soap:Envelope>"];
NSURL *myWebserverURL = [NSURL URLWithString:XMLURLAddress];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myWebserverURL];
[request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:SOAPActionURL forHTTPHeaderField:@"SOAPAction"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[sRequest dataUsingEncoding:NSUTF8StringEncoding]];
[sRequest release];
self.receivedData = [[NSMutableData alloc] init];
currentType = type;
activeConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
[receivedData setLength:0];
NSHTTPURLResponse * httpResponse;
httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"HTTP error %zd", (ssize_t) httpResponse.statusCode);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[receivedData appendData:data];
//NSLog(@"webdata: %@", data);
}
- (void)unlockErrorSilence {
errorIsShown = NO;
}
- (void)showNetworkError:(NSString*)message {
if (errorIsShown)
return;
errorIsShown = YES;
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Connection error" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil] autorelease];
[alert show];
[self performSelector:@selector(unlockErrorSilence) withObject:nil afterDelay:kErrorSilenceInterval];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error
{
NSLog(@"error with the connection");
[self showNetworkError:error.localizedDescription];
[connection release];
activeConnection = nil;
apiErrorBlock(error);
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
float progressValue = (float)totalBytesWritten/(float)totalBytesExpectedToWrite;
progressView.progress = progressValue;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"response %@",[[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease]);
CXMLDocument *xmlDoc = [[CXMLDocument alloc] initWithData:receivedData encoding:NSUTF8StringEncoding options:0 error:nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
kServerNameSpace,
@"namespace",
nil];
if (currentType == kActionTypeMarkExpired) {
NSArray *nodes = [xmlDoc nodesForXPath:@"//namespace:MarkExpiredResult" namespaceMappings:dict error:nil];
if (nodes.count>0) {
NSString *likeError = [[[[nodes lastObject] elementsForName:@"text"] lastObject] stringValue];
if (likeError.length>0)
apiErrorBlock([NSError errorWithDomain:@"com.hotspot" code:0 userInfo:@{NSLocalizedDescriptionKey:likeError}]);
else
apiResponseBlock(nil);
}
}
if (currentType == kActionTypeMarkSpam) {
NSArray *nodes = [xmlDoc nodesForXPath:@"//namespace:MarkSpamResult" namespaceMappings:dict error:nil];
if (nodes.count>0) {
NSString *likeError = [[[[nodes lastObject] elementsForName:@"text"] lastObject] stringValue];
if (likeError.length>0)
apiErrorBlock([NSError errorWithDomain:@"com.hotspot" code:0 userInfo:@{NSLocalizedDescriptionKey:likeError}]);
else
apiResponseBlock(nil);
}
}
if (currentType == kActionTypeLike) {
NSArray *nodes = [xmlDoc nodesForXPath:@"//namespace:LikeResult" namespaceMappings:dict error:nil];
if (nodes.count>0) {
NSString *likeError = [[[[nodes lastObject] elementsForName:@"text"] lastObject] stringValue];
if (likeError.length>0)
apiErrorBlock([NSError errorWithDomain:@"com.hotspot" code:0 userInfo:@{NSLocalizedDescriptionKey:likeError}]);
else
apiResponseBlock(nil);
}
}
if (currentType == kActionTypeAddComment) {
NSArray *nodes = [xmlDoc nodesForXPath:@"//namespace:CommentResult" namespaceMappings:dict error:nil];
if (nodes.count>0) {
NSString *addedID = [[[[nodes lastObject] elementsForName:@"text"] lastObject] stringValue];
if (addedID.length>0)
apiResponseBlock(@{@"addedCommentID":addedID});
else
apiErrorBlock([NSError errorWithDomain:@"com.hotspot" code:0 userInfo:@{NSLocalizedDescriptionKey:@"Error during posting comment"}]);
}
}
if (currentType == kActionTypeDeleteComment) {
NSArray *nodes = [xmlDoc nodesForXPath:@"//namespace:DeleteCommentResult" namespaceMappings:dict error:nil];
if (nodes.count>0) {
NSString *likeError = [[[[nodes lastObject] elementsForName:@"text"] lastObject] stringValue];
if (likeError.length>0)
apiErrorBlock([NSError errorWithDomain:@"com.hotspot" code:0 userInfo:@{NSLocalizedDescriptionKey:likeError}]);
else
apiResponseBlock(nil);
}
}
if (currentType == kActionTypeUnLike) {
NSArray *nodes = [xmlDoc nodesForXPath:@"//namespace:UnLikeResult" namespaceMappings:dict error:nil];
if (nodes.count>0) {
NSString *likeError = [[[[nodes lastObject] elementsForName:@"text"] lastObject] stringValue];
if (likeError.length>0)
apiErrorBlock([NSError errorWithDomain:@"com.hotspot" code:0 userInfo:@{NSLocalizedDescriptionKey:likeError}]);
else
apiResponseBlock(nil);
}
}
if (currentType == kActionTypeUploadFile) {
NSArray *nodes = [xmlDoc nodesForXPath:@"//namespace:UploadFileResult" namespaceMappings:dict error:nil];
if (nodes.count>0) {
CXMLElement *resp = nodes[0];
NSString *uploadedFileName = [[[resp elementsForName:@"text"] lastObject] stringValue];
if (uploadedFileName) {
apiResponseBlock(@{@"uploadedFileName":uploadedFileName});
}
else
apiErrorBlock([NSError errorWithDomain:@"com.hotspot" code:0 userInfo:@{NSLocalizedDescriptionKey:@"Error uploading photo"}]);
}
}
if (currentType == kActionTypeAddUser) {
apiResponseBlock(nil);
}
if (currentType == kActionTypeAddListing) {
NSArray *nodes = [xmlDoc nodesForXPath:@"//namespace:AddListingResult" namespaceMappings:dict error:nil];
if (nodes.count>0) {
CXMLElement *resp = nodes[0];
NSString *addedID = [[[resp elementsForName:@"text"] lastObject] stringValue];
if (addedID) {
apiResponseBlock(@{@"addedID":addedID});
}
else
apiErrorBlock([NSError errorWithDomain:@"com.hotspot" code:0 userInfo:@{NSLocalizedDescriptionKey:@"Error adding listing"}]);
}
}
if (currentType == kActionTypeCheckIfListingExist) {
// Set the resultNodes Array to contain an object for every instance of an node in our RSS feed
NSArray *nodes = [xmlDoc nodesForXPath:@"//namespace:BO1" namespaceMappings:dict error:nil];
if (currentType == kActionTypeGetListing) {
nodes = [xmlDoc nodesForXPath:@"//namespace:CheckIfListingExistResponse" namespaceMappings:dict error:nil];
}
NSMutableArray *results = [NSMutableArray array];
[nodes enumerateObjectsUsingBlock:^(CXMLElement *l, NSUInteger idx, BOOL *stop) {
PoiItem *new = [PoiItem new];
new.ID = @([[[[l elementsForName:@"id"] lastObject] stringValue] intValue]);
new.name = [[[l elementsForName:@"title"] lastObject] stringValue];
[results addObject:new];
[new release];
}];
apiResponseBlock(@{@"content":results});
}
if (currentType == kActionTypeGetListings || currentType == kActionTypeGetListing) {
// Set the resultNodes Array to contain an object for every instance of an node in our RSS feed
NSArray *nodes = [xmlDoc nodesForXPath:@"//namespace:BO1" namespaceMappings:dict error:nil];
if (currentType == kActionTypeGetListing) {
nodes = [xmlDoc nodesForXPath:@"//namespace:GetListingResult" namespaceMappings:dict error:nil];
}
NSMutableArray *results = [NSMutableArray array];
[nodes enumerateObjectsUsingBlock:^(CXMLElement *l, NSUInteger idx, BOOL *stop) {
PoiItem *new = [PoiItem new];
new.ID = @([[[[l elementsForName:@"id"] lastObject] stringValue] intValue]);
new.name = [[[l elementsForName:@"title"] lastObject] stringValue];
new.descriptionText = [[[l elementsForName:@"description"] lastObject] stringValue];
new.categoryCoverURL = [[[l elementsForName:@"cat_pic_url"] lastObject] stringValue];
new.address = [[[l elementsForName:@"address"] lastObject] stringValue];
new.website = [[[l elementsForName:@"website"] lastObject] stringValue];
new.phone = [[[l elementsForName:@"phone"] lastObject] stringValue];
new.discount = [[[l elementsForName:@"discount"] lastObject] stringValue];
new.entry_cost = [[[l elementsForName:@"entry_cost"] lastObject] stringValue];
new.opening_hours = [[[l elementsForName:@"opening_hours"] lastObject] stringValue];
new.event_date = [[[l elementsForName:@"event_date"] lastObject] stringValue];
new.thumbsup = @([[[[l elementsForName:@"thumbsup"] lastObject] stringValue] intValue]);
new.thumbsdown = @([[[[l elementsForName:@"thumbsdown"] lastObject] stringValue] intValue]);
float distance = [[[[l elementsForName:@"distance"] lastObject] stringValue] floatValue];
new.distance = [NSString stringWithFormat:@"%0.2f km ",distance];
NSString *lat = [[[l elementsForName:@"latitude"] lastObject] stringValue];
NSString *lon = [[[l elementsForName:@"longitude"] lastObject] stringValue];
new.location = CLLocationCoordinate2DMake([lat doubleValue], [lon doubleValue]);
NSArray *attachments = [l elementsForName:@"images"];
[new.attachments removeAllObjects];
for (CXMLElement *image in attachments) {
NSString *newURL = [[[image elementsForName:@"string"] lastObject] stringValue];
[new.attachments addObject:newURL];
}
[new setAttachments:new.attachments];
if (new.attachments.count>1) {
NSLog(@"IMAGESSS %@",new.name);
}
NSArray *allFriends = [l elementsForName:@"liked_friends"];
CXMLElement *allFriendsContainer = [allFriends lastObject];
NSArray *likes = [allFriendsContainer elementsForName:@"User"];
[new.friendsLiked removeAllObjects];
for (CXMLElement *user in likes) {
UserItem *newUser = [UserItem new];
newUser.name = [[[user elementsForName:@"name"] lastObject] stringValue];
newUser.facebookLink = [[[user elementsForName:@"fblink"] lastObject] stringValue];
// newUser.facebookLink = @"http://www.facebook.com/profile.php?id=1319733500";
NSString *cleanFbLink = [NSString stringWithString:newUser.facebookLink];
cleanFbLink = [cleanFbLink stringByReplacingOccurrencesOfString:@"profile.php?id=" withString:@""];
NSString *facebookUserID = cleanFbLink.lastPathComponent;
newUser.coverURL = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture",facebookUserID];
// [new.friendsLiked addObject:newUser];
// [new.friendsLiked addObject:newUser];
// [new.friendsLiked addObject:newUser];
[new.friendsLiked addObject:newUser];
[newUser release];
}
NSArray *allComments = [l elementsForName:@"comments"];
CXMLElement *allCommentsContainer = [allComments lastObject];
NSArray *comments = [allCommentsContainer elementsForName:@"Comment"];
[new.comments removeAllObjects];
[[SharedObjects objects].df setDateFormat:@"yyyy-MM-dd"];
for (CXMLElement *comment in comments) {
CommentItem *newComment = [CommentItem new];
newComment.ID = [[[comment elementsForName:@"id"] lastObject] stringValue];
newComment.descriptionText = [[[comment elementsForName:@"text"] lastObject] stringValue];
NSString *dateString = [[[comment elementsForName:@"date"] lastObject] stringValue];
newComment.postedDate = [[SharedObjects objects].df dateFromString:dateString];
CXMLElement *user = [[comment elementsForName:@"commented_user"] lastObject];
newComment.creatorName = [[[user elementsForName:@"name"] lastObject] stringValue];
newComment.creatorURL = [[[user elementsForName:@"fblink"] lastObject] stringValue];
NSString *cleanFbLink = [NSString stringWithString:newComment.creatorURL];
cleanFbLink = [cleanFbLink stringByReplacingOccurrencesOfString:@"profile.php?id=?" withString:@""];
NSString *facebookUserID = cleanFbLink.lastPathComponent;
newComment.coverURL = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture",facebookUserID];
[new.comments addObject:newComment];
[newComment release];
NSLog(@"adding comment text %@ %@ %@ %@",newComment.descriptionText,newComment.creatorName,newComment.creatorURL,newComment.postedDate);
}
[results addObject:new];
[new release];
}];
apiResponseBlock(@{@"content":results,@"total":@"99999"});
}
[xmlDoc release];
[connection release];
activeConnection = nil;
}
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
{
}
@end