iphone - 在 iOS 中读取文本文件中的 url 后加载 NSURL?

标签 iphone objective-c ios text-files nsurl

我在 iOS 的“我的文档”文件夹中有一个文本文件,其中包含一个如下所示的链接:@"https://www.mysite.com"

我可以通过以下方式成功读取文件:

  //READ TEXT FILE:

    NSArray *paths5 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory5 = [paths5 objectAtIndex:0];
    NSString *filePath5 = [documentsDirectory5 stringByAppendingPathComponent:@"mytext.txt"];
    NSString *myContent = [NSString stringWithContentsOfFile:filePath5 encoding:NSUTF8StringEncoding error:NULL];

NSString *myContent 是实际链接:@"https://www.mysite.com

现在我像这样通过 NSURLRequest 加载内容:

   NSURLRequest *request2 = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:myContent]]; 
           [[NSURLConnection alloc] initWithRequest:request2 delegate:self];

我遇到的问题/错误:

      Connection failed: Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0xfe75cc0 {NSUnderlyingError=0xfe86ac0 "bad URL", NSLocalizedDescription=bad URL}

但是,如果 [NSURL URLWithString:myContent]];从字面上替换为 url 字符串,例如 [NSURL URLWithString:@"https://www.mysite.com"]],然后连接工作。

这里发生了什么?为什么我不能直接将文本文件中的 url 加载到我的 URLWithString 参数中?

最佳答案

文本文件的大小如果不是很大,可以在下面找到。文本文件必须采用 utf8 编码。如果编码不同的话需要设置相应的编码line3

NSString *urlString = @"http://www.blahblah.com/myText.txt";
NSURL *myURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *string = [NSString stringWithContentsOfURL:myURL encoding:NSUTF8StringEncoding error:nil];
//                                                                  ^

关于iphone - 在 iOS 中读取文本文件中的 url 后加载 NSURL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11964123/

相关文章:

objective-c - 从 Objective-C 迁移到 Swift 并删除已转换的 Objective-C 文件

ios - 如何将 UIDatepicker 组件从日/月/年更改为年/月/日

iphone - 音频服务功能帮助

ios - 表单崩溃的 UITableView

ios - objective-C:为什么我的循环没有终止?

ios - 在 iOS 中重新加载内容拦截器

ios - 一些 iOS 设备没有声音

ios - iOS 教程 "Your Third iOS App: iCloud"过时了吗?

iphone - 上传 iPhone 应用程序但将其保密?

iphone - objective-c - 文本缩进