Creagen Creagen - 2 months ago 5x
Objective-C Question

How I properly setup an AFNetworking Get Request?

I'm trying to retrieve a line of code from my server and implement it in my


Right now, this is what my
looks like:

NSDictionary* defaults = @{@"server_addr": @""};
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];

url is the part that I need to GET from my server.

If my server has a file named Example.txt on it and within that file is a single line that like
, how can I use AFNetworking to check the file on my server and then add it to the


Here's the steps:

  1. Download the Example.txt file
  2. Read the downloaded txt file into a NSString*
  3. Save this NSString* into your NSUserDefaults

- (void)requestTextFile {
  NSString *urlString = @"";

  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

  NSURL *URL = [NSURL URLWithString:urlString];
  NSURLRequest *request = [NSURLRequest requestWithURL:URL];

  NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
  } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSString* content = [NSString stringWithContentsOfFile:filePath.relativePath encoding:NSUTF8StringEncoding error:NULL];
    NSLog(@"content = %@", content);
    //save this content to your NSUserDefaults
  [downloadTask resume];