2

我是 iOS 开发的新手。我正在开发一个应用程序,该应用程序在加载应用程序时会加载其一些设置。它曾经从外部 url 请求 JSON。

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 
#define kLatestKivaLoansURL [NSURL URLWithString: @"http://www.domain.com/jsonkeys.php"] 

#import "SyncJsonSettings.h"

@implementation SyncJsonSettings

(void)sync{

    dispatch_async(kBgQueue, ^{
        NSError* error;
        NSString *str = [NSString stringWithContentsOfURL:kLatestKivaLoansURL encoding:NSUTF8StringEncoding error:&error ];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:str waitUntilDone:YES];

    });    
}

如果互联网不可用,整个应用程序将冻结。我认为这是因为主线程。有人可以帮我在后台线程中执行此操作吗?

4

3 回答 3

2

现在,只需将其更改 waitUntilDone:YESwaitUntilDone:NO

之后做两件事实施以下之一

1)苹果的可达性

2) Tony Millio 的可达性

并检查网络状态然后主机状态(以便您可以显示正确的消息等),然后调用 URL。

于 2013-09-20T08:29:06.143 回答
1

您可以尝试将应用程序连接到以下网站:

NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com"]; // or your website
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];

if (data) {
    NSLog(@"Device is connected to the internet");
    // YOUR CODE
} else {

          UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                        message:@"Can't connect to the internet..."
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];

          [alert show];
       }
于 2013-09-20T08:02:32.837 回答
0

我在项目中使用了 Apple 版本的 Reachability.h 和 Reachability.m 来检查网络状态。

-(void)sync{

if (![self isConnected]) {
    // not connected
} else {
    dispatch_async(kBgQueue, ^{
        NSError* error;
        NSString *str = [NSString stringWithContentsOfURL:kLatestKivaLoansURL encoding:NSUTF8StringEncoding error:&error ];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:str waitUntilDone:YES];

    });

}

} - (BOOL) 已连接{

Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return !(networkStatus == NotReachable);
}
于 2013-09-20T06:50:17.733 回答