11

プロジェクトに次のコードがあり、 の代わりにiOS使用するように変換したいと考えています。トークンベースのスキームを使用するクエリを実行していますが、その方法の例が見つかりません。NSURLSessionNSURLConnectionREST APIHTTP Authentication

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:@"Username"];

NSString *token = //GET THE TOKEN FROM THE KEYCHAIN


NSString *authValue = [NSString stringWithFormat:@"Token %@",token];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];


if ([NSURLConnection canHandleRequest:request]){
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [NSURLConnection sendAsynchronousRequest:request queue:self.fetchQueue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

                               if (!connectionError) {
                                   NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                                   if (httpResponse.statusCode == 200){
                                       NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil];

                                       //Process the data
                                   }
                               }

                           }];
}
4

3 に答える 3

3

これは Swift ですが、ロジックは同じです。

    let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
    let url  = NSURL(string: "some url")

    let request = NSMutableURLRequest(URL: url!)
    request.setValue("value", forHTTPHeaderField: "header field")

    let urlSession = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: NSOperationQueue.mainQueue())


    let dataTask = urlSession.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
    }

    dataTask.resume()
于 2015-09-16T12:42:58.237 に答える