IOS7 NSURLConnection没有任何反应

时间:2013-11-24 22:29:39

标签: ios nsurlconnection

我是IOS编程的新手,想要将用户的位置发送到服务器。我在互联网上关注了iOS开发人员库和教程,但是当我运行代码时没有任何反应。我正在使用iOS模拟器,它可以很好地为我提供模拟位置,并获得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

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

您正在单独的线程上执行NSURLConnection。并且线程在收到响应之前退出。您需要在主线程上执行NSURLConnection,或者需要保持线程运行直到收到响应。