0
votes

I have a text file in My Documents folder in iOS that contains a link that looks like this inside: @"https://www.mysite.com"

I can read the file successfully with:

  //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 is the actual link: @"https://www.mysite.com

Now I load the content via NSURLRequest like so:

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

The Problem/error I get:

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

BUT, If [NSURL URLWithString:myContent]]; is replaced literally with the url string such as [NSURL URLWithString:@"https://www.mysite.com"]], then the connection works.

What's happening here? Why can't I just load the url in the text file into my URLWithString parameter?

1
Could you try to trim your string from any whitespace characters? filePath5 = [filePath5 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];Sylvain Guillopé
I still get the same error...sunny

1 Answers

6
votes

The size of the text file if it is a not gigantic, is available reasonable below. the text file must be in utf8 encoding. If a different encoding if you need to set the appropriate encoding 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];
//                                                                  ^