IOS7 NSURLConnection 没有任何反应

标签 ios nsurlconnection

我是 IOS 编程的新手,想将用户的位置发送到服务器。我在 Internet 上关注了 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

如有任何帮助,我们将不胜感激。

最佳答案

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

关于IOS7 NSURLConnection 没有任何反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20181932/

相关文章:

cocoa - NSURL 来自 NSURLConnection?

ios - 如何在 watch 套件中显示通知,其中 iPhone 应用程序已经显示通知

ios - Xcode:无法检查应用程序包

ios - 是什么导致 NSURLConnection 在完成之前停止接收?

ios - 为什么使用 NSURLConnection sendAsynchronousRequest 建立与数据库的连接会延迟?

iphone - NSURLConnection 在文件下载时收到 'False'

objective-c - 从多个 ImageView 中识别特定 ImageView

ios - 查找与特定字符串的匹配项

ios - 在新 ViewController 中使用代码时发送到实例的 UIButton 无法识别的选择器

ios - NSURLConnection的奇怪错误代码4294966295