How I properly setup an AFNetworking Get Request?

谁说胖子不能爱 提交于 2019-12-25 04:23:06

问题


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

Right now, this is what my appdelegate.m looks like:

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

The http://156.92.15.802 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 http://156.92.15.802, how can I use AFNetworking to check the file on my server and then add it to the NSUserDefaults?


回答1:


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 = @"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];
}



回答2:


I'm using the same to POST onto server. But are you sure you want to work with AFNetworking, i think NSURLConnection will also work.

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:stringURL]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

[manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
    //do not put image inside parameters dictionary as I did, but append it!

}
success:^(NSURLSessionDataTask *task, id responseObject)
 {
     //here is place for code executed in success case
 }
failure:^(NSURLSessionDataTask *task, NSError *error)
{
     //here is place for code executed in error case
 }];


来源:https://stackoverflow.com/questions/38757740/how-i-properly-setup-an-afnetworking-get-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!