Я довольно новичок в программировании IOS и хочу, чтобы местоположение пользователя на сервере. Я следил за библиотекой разработчиков iOS и учебными пособиями в Интернете, но ничего не происходит, когда я запускаю код. Я использую симулятор iOS, и он дает мне макет местоположения хорошо, и я получаю экземпляр NSURLConnection
. Однако на серверной стороне ничего не происходит.IOS7 NSURLConnection ничего не происходит
#import "JLSViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "JLSEventData.h"
@interface JLSViewController()
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) NSMutableArray *locations;
@end
@implementation JLSViewController
NSMutableData *responseData = nil;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.locations = [[NSMutableArray alloc] init];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)enabledStateChanged:(id)sender
{
if (self.switchEnabled.on)
{
[self.locationManager startUpdatingLocation];
}
else
{
[self.locationManager stopUpdatingLocation];
}
}
- (void)beginBackgroundUpdateTask: (CLLocation *)location {
}
- (void)endBackgroundUpdateTask {
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
if (newLocation == nil) {
return;
}
if (oldLocation != nil) {
if (newLocation.coordinate.latitude == oldLocation.coordinate.latitude &&
newLocation.coordinate.longitude == oldLocation.coordinate.longitude) {
return;
}
}
NSError *error = nil;
JLSEventData *eventData = [[JLSEventData alloc] initWithLocation: newLocation];
NSString *strData = [eventData toJSON:error];
if (error != nil){
return;
}
if (self.locations.count>5)
[self.locations removeObjectAtIndex:0];
[self.locations addObject:strData];
NSData *requestBodyData = [NSJSONSerialization dataWithJSONObject:self.locations options:NSJSONWritingPrettyPrinted error:&error];
if (error != nil){
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//[self beginBackgroundUpdateTask:newLocation];
// Send a synchronous request
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: "http://localhost:8080/mywebservice"]];
[urlRequest setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setHTTPMethod:@"POST"];
//[urlRequest setTimeoutInterval:20];
//NSJSONSerialization dataWithJSONObject
urlRequest.HTTPBody = requestBodyData;
// Create url connection and fire request
[urlRequest setHTTPBody:[NSData dataWithBytes:[strData UTF8String] length:strlen([strData UTF8String])]];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (conn!=nil){
//receivedData = nil;
}
});
}
#pragma mark - NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"==>didReceiveResponse");
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"==>didReceiveData");
// Append the new data to the instance variable you declared
[responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
NSLog(@"Succeeded! Received %d bytes of data",[responseData length]);
responseData = nil;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
/*
*
*/
- (void)parseData {
//Do something
}
@end
Любая помощь будет оценена по достоинству.
Вы проверили, достигнут ли ваш вызов NSURLConnection? (с точками прерывания или NSLog?) –
Да, экземпляр NSURLConnection не имеет значения null, означает ли это, что соединение было привязано, делает это ?: conn ======> Хотя я думаю, что это должно дать мне ошибка в любом случае, если есть какая-либо ошибка, не так ли? –
sunghun