简体   繁体   中英

Error Convert NSString TO NSURL Xcode 8 Error code 256

Convert NSString To NSURL

this is my code but i reciving null result

NSString *Mystr = [NSString stringWithFormat:@"http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in (\"USDEUR\")&env=store://datatables.org/alltableswithkeys"];




NSURL *URLOne = [[NSURL alloc] initWithString:[Mystr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];

NSError *error1;
NSString *strresult = [NSString stringWithContentsOfURL:URLOne
                                                encoding:NSASCIIStringEncoding
                                                   error:&error1];


NSLog(@"%@", strresult);

here is my Error

Error Domain=NSCocoaErrorDomain Code=256 "The file “yql” couldn't be opened." UserInfo={ NSURL=http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDEUR%22)&env=store://datatables.org/alltableswithkeys }

In no particular order:

  • The stringWithContentsOfURL method is not intended to be used for fetching network URLs. You should be using the NSURLSession API for that.
  • You can't just arbitrarily URL-encode a URL like that. I suspect that you only want to encode the contents of the q parameter, and possibly the contents of the env parameter. You have to encode those separately and then concatenate them. If you try to encode the entire string, your URL will start with http%3A%2F%2F ....
  • That's not a good method for encoding URL query string data. Among other things, it won't encode a bunch of special characters that are technically legal in query string but that can result in misbehavior (eg equals signs and ampersands). Instead, do this:

     NSString *qParameterEncoded = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (__bridge CFStringRef)qParameter, NULL, CFSTR(":/?#[]@!$&'()*+,;="), kCFStringEncodingUTF8); 

    or do the equivalent with stringByAddingPercentEncodingWithAllowedCharacters: and a custom NSCharacterSet .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM