ios - 我如何正确设置 AFNetworking Get 请求?

标签 ios objective-c afnetworking

我正在尝试从我的服务器检索一行代码并在我的 NSUserDefaults 中实现它。

现在,这就是我的 appdelegate.m 的样子:

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

http://156.92.15.802 url 是我需要从服务器获取的部分。

如果我的服务器上有一个名为 Example.txt 的文件,并且该文件中有一行类似 http://156.92.15.802,我如何使用 AFNetworking 检查文件我的服务器,然后将其添加到 NSUserDefaults?

最佳答案

步骤如下:

  1. 下载Example.txt文件
  2. 将下载的txt文件读入NSString*
  3. 将此 NSString* 保存到您的 NSUserDefaults

- (void)requestTextFile {
  NSString *urlString = @"http://156.92.15.802/Example.txt";

  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];
}

关于ios - 我如何正确设置 AFNetworking Get 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38757740/

相关文章:

iOS 5 Storyboard segue 复制音乐应用程序的专辑轨道 View

ios - 在横向模式下在 iPad 上呈现 UIImageViewController 时崩溃

objective-c - IBInspectable 属性在 initWithCoder 中没有其值 : initializer

objective-c - 在 OS X 中模拟单击和拖动

ios - AFNetworking 2.0.0-RC2 : No visible @interface for 'DNHackerNewsAPIClient' declares the selector 'getPath:parameters:success:failure:' ?

javascript - 检测浏览器/设备是否支持双击事件

ios - 如何使用 CAMediaTimingFunction 模拟 tableview 的移动

ios - 图像选择器 Controller 自定义背景

ios - 通过 AFNetworkingLibrary 将 Url 传递给 ImageView

ios - 构建静态框架和内部链接其他开源库的设计方法