Connecting from IOS to ASP.Net Webservce - asp.net

I am writing an IPad App that needs to connect to a webservice that returns and integer like this:
<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">0</int>
My code looks like this
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:verficationURL]];
[request setHTTPMethod:#"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(void) connection: (NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.responseData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *result = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(#"array: %s", result);
}
The connection does finish loading, but I am unable to get the value 0 out of the result. What is the right way to do this. Thank You

I'm assuming you get the result, so will respond only regarding the parsing.
I'm usually using XMLReader for easy xml parsing. There are also other third-party libraries that you can use, or use NSXMLParsing directly, however, you'll need to write a little more code for that.
Using it, the code for parsing would look like this:
NSError *error = nil;
NSDictionary *dict = [XMLReader dictionaryForXMLData:self.responseData error:&error];
NSNumber *result = [dict valueForKey:#"int"];
if(error||!result){
// handle error (either the result is not xml format, or the xml doesn't contain a 'int' key)
}
else {
// handle result
}
I haven't tested this exact code, but it should be mostly correct.

Please create REST based Web Services as it becomes very easy to interact with the DB and move on to JSON.

Related

Unrecognized selector occurring after Lightweight Core Data migration

I'm getting an unrecognized selector on a newly added field to my Core Data (SQLite) db on iOS. I added a new model version as directed using Xcode's Editor menu, and then verified that new version is the current one. I made sure also that the .h and .m files for the modified table were updated, though I did this by hand (how to have these generated for you?). Nothing unusual though, just a String type field.
The problem seems to be that the lightweight migration never takes place by the time code is run that tries to reference the database object. Tring to access newFieldName gives:
-[MyEntity newFieldName]: unrecognized selector sent to instance 0x852b510
2014-03-27 13:26:21.734 ASSIST for iPad[41682:c07] *** Terminating app due to
uncaught exception 'NSInvalidArgumentException', reason: '-[MyEntity newFieldName]:
unrecognized selector sent to instance 0x852b510'
The line of code that generates the above error is the only line in the for loop below:
DataStoreCoreData *dStore = [[DataStoreCoreData alloc] initWithDataItemDescription:did];
for (MyEntity *myEnt in [dStore objects])
NSString *name = [myEnt newFieldName];
As mentioned, when I examine the SQLite db it has no new field in it, which makes sense given the error. So I also stepped through the execution of the code that is supposed to do the migration and it seems to work fine. Success. It looks like the following:
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"ASSIST.sqlite"]];
// handle db upgrade
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error])
NSLog(#"\r\n Fail. [error localizedDescription]: %#", [error localizedDescription]);
else
NSLog(#"\r\n Success");
This is the 6th db version upgrade. All have been lightweight migrations with no unusual problems. Should not the above code force the SQLite db to reflect the new schema? How do I get it to do so, or is there another problem here?
I finally discovered the answer. The code I provided with the question is only part of the code required to be modified when making minimal changes to the database (lightweight migration). You also need to specify the new version when you create the object model. Notice "MyNewVersion" in the code below. You are supposed to update this parameter to reflect the new version you created and then selected as the current Model Version:
NSString *path = [[NSBundle mainBundle] pathForResource:#"MyNewVersion" ofType:#"mom" inDirectory:#"ASSIST.momd"];
NSURL *momURL = [NSURL fileURLWithPath:path];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];

Can not create NSError: unrecognized selector

I am trying to create a NSError category to make pre-defined errors based upon status codes. However, any time that I try to create a NSError from my category, I get a
+[NSError errorWithDomain:code:userInfo:]: unrecognized selector sent to class 0x2b2b20
I have also tried calling the instance version of the NSError Initializer but this has the same result.
+(NSError*)errorOfType:(ErrorType)errorType inClassNamed:(NSString*)_nsClassName andMessage:(NSString*)_nsMessage
{
return [[[self class] alloc]initWithType:errorType inClassNamed: _nsClassName andMessage:_nsMessage];
}
#pragma mark -
#pragma mark - Init
-(id)initWithType:(ErrorType)errorType inClassNamed:(NSString*)_nsClassName andMessage:(NSString*)_nsMessage
{
NSInteger _nCode = [self codeFromErrorType:errorType];
NSDictionary *_nsUserInfo = [self localizedDescriptionForErrorType:errorType andMessage:_nsMessage];
NSLog(#"Why Does this fail? Is this Nil? %#, \n%i, \n%#", _nsClassName, _nCode, _nsUserInfo);
if ([self respondsToSelector:#selector(initWithDomain:code:userInfo:)]) {
if (self = [self initWithDomain:_nsClassName code:_nCode userInfo:_nsUserInfo]){
}
}else{
NSLog(#"NSERROR Did not create!!!");
}
return self;
}
When I run this code calling the static method, The output is:
2013-05-10 17:46:18.851 BMPassSDK-DemoApp[99692:c07] Why Does this fail? Is this Nil? Domain,
107,
{
NSLocalizedDescription = "A connection to the server could not be made. Please Try again later. ";
}
2013-05-10 17:46:18.851 BMPassSDK-DemoApp[99692:c07] NSERROR Did not create!!!
2013-05-10 17:46:18.852 BMPassSDK-DemoApp[99692:c07] +[NSError errorWithDomain:code:userInfo:]: unrecognized selector sent to class 0x2b2b20
(lldb) po 0x2b2b20
$0 = 2829088 NSError
(lldb)
Anyone have any suggestions on what I am missing?
When I first made this class it was a subclass of NSError. Later, when I tried to convert it from a subclass to category, I accidentally renamed my header file's base class to type NSObject instead of NSError. This is of course what was causing my issue because NSObjects do not respond to the selector initWithDomain:code:userInfo.
Anyways, thanks everyone for looking. Hope it helps someone else.

can't see the banner on my simulator

I want to add Admob in my app, the compilation is correct, but I can not see the banner on my simulator.
The app is for iPad in landscape mode.
I added the UUID of my macbook to the variable TEST_DEVICE_ID.
Could you help me ??
Thanks
bannerView_ = [[GADBannerView alloc]
initWithFrame:CGRectMake(0.0,
self.view.frame.size.height -
GAD_SIZE_320x50.height,
GAD_SIZE_320x50.width,
GAD_SIZE_320x50.height)];
bannerView_.adUnitID = MY_BANNER_UNIT_ID;
bannerView_.rootViewController = self;
[self.view addSubview:bannerView_];
[bannerView_ loadRequest:[GADRequest request]];
GADRequest *request = [GADRequest request];
request.testDevices = [NSArray arrayWithObjects:
GAD_SIMULATOR_ID,
#"TEST_DEVICE_ID",
nil];
First of all, you're not actually passing the request with testDevices to AdMob. To do that, you'll want to write:
GADRequest *request = [GADRequest request];
request.testDevices = [NSArray arrayWithObjects:
GAD_SIMULATOR_ID,
#"TEST_DEVICE_ID",
nil];
[bannerView_ loadRequest:request];
Now when you actually release, you'll want to be able to get live ads too. To find out more information, implement GADBannerViewDelegate and log why you aren't getting an ad:
- (void)adView:(GADBannerView *)view
didFailToReceiveAdWithError:(GADRequestError *)error {
NSLog(#"Failed to receive ad with error: %#", [error localizedFailureReason]);
}
Remember you'll need to add bannerView_.delegate = self; to set the delegate for this method to be fired.

CLLocationManager not returning correct location

I'm working on an app where it checks your location every minute or so to see if your location changed. I am simulating the location changes by using a simulated location in xCode. First I'll do London, then when it updates that I'll change it to something like Tokyo, and then when it's time to check the location again it just won't update, it still thinks it's in London.
-(void)recheckLocation{
locationManager = nil;
[recheckLocation invalidate];
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
geocoder = [[CLGeocoder alloc] init];
[locationManager stopUpdatingLocation];
// Reverse Geocoding
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks objectAtIndex:0];
NSString *Location = [NSString stringWithFormat:#"%#, %#",placemark.locality, placemark.administrativeArea];
recheckLocation = [NSTimer scheduledTimerWithTimeInterval:60.0f target:self selector:#selector(recheckLocation) userInfo:nil repeats:YES];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
No matter how many times I changed the location it just keeps giving me the same location every time rather than the correct one. Can someone tell me what I am doing wrong?
Its bit older post and I am having basic knowledge in CLLocationManager stuff, but still I am trying to address the problem. I understand from your above code that CLLocationManager is recreated everytime. CLLocationManager is like a singleton class you don't need to recreate everytime. You just need to call [locationManager startUpdatingLocation]; .
Also everytime you are calling [geocoder reverseGeocodeLocation:xxx]. Probably you need to find accuracy before you do this so that it will not get called again and again.

timeout stringwithcontentsofurl

I have this call to stringwithcontentsofurl:
[NSString stringWithContentsOfURL:url usedEncoding:nil error:nil];
How can I give that a simple timeout?
I don't want to use threads or operation queues (the content of the url is about 100 characters), I just don't want to wait too long when the connection is slow.
Here's my take on it:
NSString* link = #"http://example.com";
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:link] cachePolicy:0 timeoutInterval:5];
NSURLResponse* response=nil;
NSError* error=nil;
NSData* data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString* stringFromServer = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
In this case, you might be best off using the NSURLConnection class method +sendSynchronousRequest:returningResponse:error:; it'll return a data object you can initialize your string with (using -initWithData:encoding:). You can specify a timeout by creating an NSURLRequest using its -initWithURL:cachePolicy:timeoutInterval: method, then pass that request as the first parameter of +sendSynchronousRequest:returningResponse:error:.

Resources