如何更改sendSynchronousRequest:urlRequest,因为已弃用

时间:2016-11-15 08:56:22

标签: ios objective-c deprecated

我是Objective-C的首发,我有一个方法

- (void)getAltitudeFromElevationFromAlt:(float)latitude Long:(float)longitude{
    dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *apiKey = @"IzaSyA5CDPUYC7GY5PzJdu_K4ouRy55gm3R5BO4";
        NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/elevation/json?locations=%f,%f&key=%@", latitude, longitude, apiKey];
        // Send a synchronous request

        NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:address]];
        NSURLResponse * response = nil;
        NSError * error = nil;
        NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                              returningResponse:&response
                                                          error:&error];

       NSString *str = @"No Data";
        if (error == nil)
        {
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
            str = [NSString stringWithFormat:@"%@", dictionary[@"results"][0][@"elevation"]];
            //  NSLog(@"text  = %@", dictionary[@"results"][0][@"elevation"]);
            NSLog(@"str = %@", str);
            dispatch_async( dispatch_get_main_queue(), ^{
                _altitudeMeterLabel.text = str;
            });
        }
    });
}

请帮助改变此序列

NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];

4 个答案:

答案 0 :(得分:2)

使用Input : {localhost, karuma} SystemName : {KARUMA, KARUMA} Manufacturer : {Hewlett-Packard, Hewlett-Packard} Model : {h9-1400a, h9-1400a} PhysicalMemory : {17115000832, 17115000832} LogicalProcessors : {8, 8} OSCaption : {Microsoft Windows 10 Pro, Microsoft Windows 10 Pro} OSArchitecture : {64-bit, 64-bit} ServicePackMajorVersion : {0, 0} 异步请求:

NSURLSession

注意:

不需要全局- (void)getAltitudeFromElevationFromAlt:(float)latitude Long:(float)longitude { NSString *apiKey = @"IzaSyA5CDPUYC7GY5PzJdu_K4ouRy55gm3R5BO4"; NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/elevation/json?locations=%f,%f&key=%@", latitude, longitude, apiKey]; // Send an ASYNCHRONOUS request NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:address]]; [[[NSURLSession sharedSession] dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSString *str = @"No Data"; if (error) { NSLog(@"%@", error); } else { NSError * jsonError = nil; NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError]; if (jsonError) { NSLog(@"%@", jsonError); } else { str = [NSString stringWithFormat:@"%@", dictionary[@"results"][0][@"elevation"]]; // NSLog(@"text = %@", dictionary[@"results"][0][@"elevation"]); NSLog(@"str = %@", str); } dispatch_async( dispatch_get_main_queue(), ^{ _altitudeMeterLabel.text = str; }); } }] resume]; } 块,因为无论如何都会将数据任务分派到后台线程。

答案 1 :(得分:0)

NSURLSession dataTaskWithRequest

一起使用
- (void)getAltitudeFromElevationFromAlt:(float)latitude Long:(float)longitude
{
    NSString *apiKey = @"IzaSyA5CDPUYC7GY5PzJdu_K4ouRy55gm3R5BO4";
    NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/elevation/json?locations=%f,%f&key=%@", latitude, longitude, apiKey];

    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:address]];
    NSURLResponse * response = nil;
    NSString *str = @"No Data";

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                         completionHandler:
     ^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error == nil)
    {
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        str = [NSString stringWithFormat:@"%@", dictionary[@"results"][0][@"elevation"]];
        //  NSLog(@"text  = %@", dictionary[@"results"][0][@"elevation"]);
        NSLog(@"str = %@", str);
        dispatch_async( dispatch_get_main_queue(), ^{
            _altitudeMeterLabel.text = str;
        });
    }
    }];

     [task resume];    
}     

答案 2 :(得分:0)

请尝试以下代码

    - (void)getAltitudeFromElevationFromAlt:(float)latitude Long:(float)longitude{
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSString *apiKey = @"IzaSyA5CDPUYC7GY5PzJdu_K4ouRy55gm3R5BO4";
    NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/elevation/json?locations=%f,%f&key=%@", latitude, longitude, apiKey];
   // Send a synchronous request

    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:address]
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *error) {
                NSString *str = @"No Data";
                if (error == nil)
                {
                    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
                    str = [NSString stringWithFormat:@"%@", dictionary[@"results"][0][@"elevation"]];
                    //  NSLog(@"text  = %@", dictionary[@"results"][0][@"elevation"]);
                    NSLog(@"str = %@", str);
                    dispatch_async( dispatch_get_main_queue(), ^{
                        _altitudeMeterLabel.text = str;
                    });
                }

            }] resume];
    });

}

答案 3 :(得分:0)

同步方法在iOS 9中已弃用,因为它阻止了当时的主线程。所以不建议发送同步执行此操作。

如果确实需要,您可以创建NSUrlSession类别以同步执行您的请求。

#import "NSURLSession+Sync.h"

@implementation NSURLSession (Sync)

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request
                 returningResponse:(__autoreleasing NSURLResponse **)responsePtr
                             error:(__autoreleasing NSError **)errorPtr {
    dispatch_semaphore_t    sem;
    __block NSData *        result;

    result = nil;

    sem = dispatch_semaphore_create(0);

    [[[NSURLSession sharedSession] dataTaskWithRequest:request
                                     completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                         if (errorPtr != NULL) {
                                             *errorPtr = error;
                                         }
                                         if (responsePtr != NULL) {
                                             *responsePtr = response;
                                         }  
                                         if (error == nil) {  
                                             result = data;  
                                         }  
                                         dispatch_semaphore_signal(sem);  
                                     }] resume];  

    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);  

    return result;  
}
@end

并在以下代码中使用:

  NSData * data = [NSURLSession sendSynchronousRequest:urlRequest returningResponse:&response error:&error];