2

いくつかのデータを提供する REST サービスを作成しました。パスコードで保護されています。

データを取得して、アプリにある sqlLite db に詰め込むバックグラウンド プロセスを作成しようとしています。

最初は次を使用して認証なしでこれを行いました:

- (void) callWebService {
    dispatch_sync(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL:
                        scoularDirectoryURL];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
    });
}

これはうまくいきましたが、それに認証を追加できるとは思いません。できればそれを使うだけです。

私が探しているのは、ユーザー/パスワード認証を使用した NSURLSession の素晴らしく簡単な説明です。

4

2 に答える 2

0

私にとっては、次のコードが機能します。

NSString *userName=@"user:";
NSString *userPassword=@"password";
NSString *authStr= [userName stringByAppendingString:userPassword];
NSString *url=@"http://000.00.0.0:0000/service.json";

NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]

                       completionHandler:^(NSURLResponse *response,
                                           NSData *data, NSError *connectionError)

NSDictionary *theDictionary = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:0
                                                                    error:NULL];

 NSDictionary *host = [theDictionary objectForKey : @"host"];
         // json nested
            self.label.text = [host objectForKey:@"key1"];
            self.label.text = [host objectForKey:@"key2"];

よろしく

于 2016-04-21T20:28:31.220 に答える