【问题标题】:Getting date from web, returns nil从网上获取日期,返回零
【发布时间】:2021-10-24 14:54:22
【问题描述】:

检查以从 Google 获取当前时间和日期。第一个选项有效,但不是最好的方法,因为它使用的是一种折旧的方法,并且等待一切都用同步方法完成并不是很好的用户体验。

-(NSDate*)timeAndDateFromWeb{
    

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                    initWithURL:[NSURL URLWithString:@"https://google.co.uk"]];
    [request setHTTPMethod:@"GET"];
    NSHTTPURLResponse *httpResponse = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&httpResponse error:nil];
    NSString *dateString = [[httpResponse allHeaderFields] objectForKey:@"Date"];
    DebugLog(@" *** GOOGLE DATE:  %@ ****",dateString);
    if (httpResponse){
        hasDataConnection = YES;
       
    }
    else{
        hasDataConnection = NO;
       
    }
    
    // Convert string to date object
    NSDateFormatter *dateformatted = [NSDateFormatter new];
    [dateformatted setDateFormat:@"E, d MMM yyyy HH:mm:ss zzz"];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
    [dateformatted setLocale:locale];
    
    return [dateformatted dateFromString:dateString];
}

尽管我的日期字符串返回 nil,但尝试适应它几乎就在那里:[dateformatted dateFromString:dateString];

    NSURL *url = [NSURL URLWithString:@"https://google.co.uk"];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    NSHTTPURLResponse *httpResponse = nil;
    NSString *dateString = [[httpResponse allHeaderFields] objectForKey:@"Date"];
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
      if (error) {
          hasDataConnection = NO;
          //NSLog(@"\n\n ----> Not connected Error,%@", [error localizedDescription]);
      }
      else {
          //NSLog(@"\n\n -----> connected:  %@", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
          hasDataConnection = YES;
       
          
      }
    }];
    
    
    // Convert string to date object
    NSDateFormatter *dateformatted = [NSDateFormatter new];
    [dateformatted setDateFormat:@"E, d MMM yyyy HH:mm:ss zzz"];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
    [dateformatted setLocale:locale];

    DebugLog(@" *** GOOGLE DATE:  %@ ****",[dateformatted dateFromString:dateString]);
    
    return [dateformatted dateFromString:dateString];

【问题讨论】:

  • 在第二个选项中,您将在 DebugLog(@" *** GOOGLE DATE: %@ ****",dateString); 中获得输出
  • 啊,是的。错字,已编辑,日期仍然没有值

标签: ios objective-c nsdate nsurlconnection


【解决方案1】:

当你从同步切换到异步时,不能像以前一样返回值。

当您调用sendAsynchronousRequest 方法时,它会启动一个后台任务,但您的线程会立即继续工作。这就是为什么httpResponse 和dateString 都是null。

因此,您应该将返回类型更改为void,因为您不能立即返回结果,并添加一个回调,该回调将在工作完成时运行。并在完成任务时处理您的格式:

- (void)timeAndDateFromWeb:(void (^)(NSDate *))completion {
    NSURL *url = [NSURL URLWithString:@"https://google.co.uk"];
    NSURLSessionTask *task = [NSURLSession.sharedSession
     dataTaskWithURL:url
     completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
//            hasDataConnection = NO;
            //NSLog(@"\n\n ----> Not connected Error,%@", [error localizedDescription]);
        }
        else if ([response isKindOfClass:NSHTTPURLResponse.class] ) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            NSString *dateString = [[httpResponse allHeaderFields] objectForKey:@"Date"];
            
            // Convert string to date object
            NSDateFormatter *dateformatted = [NSDateFormatter new];
            [dateformatted setDateFormat:@"E, d MMM yyyy HH:mm:ss zzz"];
            NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
            [dateformatted setLocale:locale];
            
//            DebugLog(@" *** GOOGLE DATE:  %@ ****",[dateformatted dateFromString:dateString]);
            
            completion([dateformatted dateFromString:dateString]);
            //NSLog(@"\n\n -----> connected:  %@", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
//            hasDataConnection = YES;
            
            
        }
    }];
    [task resume];
}

所以这个方法的结果会返回到block,和后台任务的结果一样。

不要忘记,它将在后台线程上调用,与下载任务完成块相同。所以如果你想改变一些 UI,你需要回到主线程:

[self timeAndDateFromWeb:^(NSDate *date) {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"%@", date);
        // UI changes
    });
}];

或者,您可以在返回结果之前将其移至函数内的主线程:

NSDate *date = [dateformatted dateFromString:dateString];
dispatch_async(dispatch_get_main_queue(), ^{
    completion(date);
});

【讨论】:

  • 出色的答案和非常有用的解释,谢谢。在我得到return [dateformatted dateFromString:dateString]; 和[self timeAndDateFromWeb] 的返回值之前。这不适用于新的块方法
  • @JSA986 究竟是怎么回事?您在控制台中看不到带有日期的消息?请提供您现在如何调用它的代码
  • @JSA986 - philip 的答案是正确的,只有一个问题,您在dateString 中得到的输出是什么
  • dateString 在块中正常返回。这个问题,现在用另一种方法调用它:NSDate * date = [self timeAndDateFromWeb]。如果我为它定义一个变量(并且已经将dateString 切换到主线程),它的nil
  • 我可以使用:[self timeAndDateFromWeb:^(NSDate *date) { dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"%@", date); // UI changes }); }]; 在我的其他方法中抛出Incompatible block pointer types passing 'BOOL (^)(void)' to parameter of type 'dispatch_block_t _Nonnull' (aka 'void (^)(void)')。用__block 为日期声明变量总是在块外返回null
猜你喜欢
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多