如何正确设置AFNetworking获取请求? [英] How I properly setup an AFNetworking Get Request?
本文介绍了如何正确设置AFNetworking获取请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从服务器中检索一行代码,并在我的 NSUserDefaults
中实现它。
I'm trying to retrieve a line of code from my server and implement it in my NSUserDefaults
.
现在,这就是我的 appdelegate.m
的样子:
Right now, this is what my appdelegate.m
looks like:
NSDictionary* defaults = @{@"server_addr": @"http://156.92.15.802"};
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
http://156.92.15.802
url是我需要从服务器中获取的部分。
The http://156.92.15.802
url is the part that I need to GET from my server.
如果我的服务器上有一个名为Example.txt的文件,并且该文件中有一行,例如 http://156.92.15.802
,如何使用AFNetworking检查服务器上的文件,然后将其添加到 NSUserDefaults
?
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
?
推荐答案
步骤如下:
- 下载
Example.txt
文件 - 读取下载的
txt
文件放入NSString *
- 将此
NSString *
保存到您的NSUserDefaults
- Download the
Example.txt
file - Read the downloaded
txt
file into aNSString*
- Save this
NSString*
into yourNSUserDefaults
- (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];
}
这篇关于如何正确设置AFNetworking获取请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文