这是my URL。我需要从这个URL获取数据..这将返回英文单词的值..但如果我给出像“ParaQuéVolviste”这样的参数..那么它返回null ..请帮助我..
我的代码是
NSURLConnection * connectionGetISRC=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://ws.spotify.com/search/1/track.json?q=Para Qué Volviste"]] delegate:self];
[connectionGetISRC start];
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
dataJson=[NSMutableData data];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"dat %@",data);
[dataJson appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"error %@",error.description);
[hud hide:YES];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
id dict=[NSJSONSerialization JSONObjectWithData:dataJson options:kNilOptions error:nil];
NSLog(@"dataJson %@",dataJson);
NSLog(@"dicvt %@",dict);
}
答案 0 :(得分:3)
您应该在启动连接之前对请求参数进行编码,如下所示
NSString* urlString = [NSString stringWithFormat:@"http://ws.spotify.com/search/1/track.json?q=%@",[@"Para Qué Volviste" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL* url = [NSURL URLWithString:urlString];
NSURLConnection * connectionGetISRC=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url] delegate:self];
[connectionGetISRC start];
答案 1 :(得分:3)
看起来您网址中的空格是个问题。试试这个连接字符串
NSString *str=[NSString stringWithFormat:@"http://ws.spotify.com/search/1/track.json?q=Para Qué Volviste"];
str=[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLConnection * connectionGetISRC=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]] delegate:self];
[connectionGetISRC start];
答案 2 :(得分:0)
您希望百分比转义您的网址参数,但请注意不要被stringByAddingPercentEscapesUsingEncoding
诱惑。这样可以很好地处理空间(这是当前的问题),但是如果你有一些其他的保留字符,它就会失败(例如,如果你的参数中包含&
或+
个字符,那就很明显了) 。如果你想处理这些类型的字符,你真的应该使用CFURLCreateStringByAddingPercentEscapes
代替:
NSString* urlString = [NSString stringWithFormat:@"http://ws.spotify.com/search/1/track.json?q=%@", [self percentEscapeString:@"Para Qué Volviste"]];
NSURLConnection * connectionGetISRC=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString] delegate:self];
// [connectionGetISRC start];
在哪里,percentEscapeString
来电CFURLCreateStringByAddingPercentEscapes
:
- (NSString *)percentEscapeString:(NSString *)string
{
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
NULL,
(CFStringRef)@":/?@!$&'()*+,;=",
kCFStringEncodingUTF8));
}
另外,initWithRequest:delegate:
会自动启动连接,因此您不应手动调用start
方法。 start
的{{3}}表示:
仅当您使用
initWithRequest:delegate:startImmediately:
方法创建连接并为NO
参数提供startImmediately
时,才需要调用此方法。