处理NSURL中的特殊字符

时间:2014-09-29 15:26:48

标签: ios afnetworking nsurl

我有这个代码到图像的网址,我的网址没有什么问题它包含\ u和xcode认为它是特殊字符所以我通过在我的网址添加\ u来逃避它 但是当我通过它时

fullPath = [NSString stringWithFormat:@"http:\\www.school-link.net\\uploads\\%@",image_url];
    NSLog(@"file path  %@",fullPath);
    //i try escape space by this code it dosnt work 
   //fullPath = [fullPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [[NSURL alloc]initWithString:fullPath];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];



 AFHTTPRequestOperation *posterOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    posterOperation.responseSerializer = [AFImageResponseSerializer serializer];
    [posterOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Response: %@", responseObject);
        image_view.image = responseObject;

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Image request failed with error: %@", error);
    }];
    [[NSOperationQueue mainQueue] addOperation:posterOperation];
    [posterOperation start];

它给我错误,任何想法 谢谢大家

  

图片请求失败并显示错误:错误域= NSURLErrorDomain代码= -1000"错误的网址" UserInfo = 0x8f9f900 {NSUnderlyingError = 0x9a94cf0" bad URL",NSLocalizedDescription = bad URL}

2 个答案:

答案 0 :(得分:2)

您的网址格式错误。现在你有:

http:\\www.school-link.net\\uploads\\%@

那些反斜杠应该是正斜杠。例如:

http://www.school-link.net/uploads/%@

现在,您可以将image_url附加到网址,并假设image_url没有导致网址格式错误,您的请求将会通过。

答案 1 :(得分:1)

使用NSUTF8String编码。它将解决问题。例如

NSString *strURL = [NSString stringWithContentsOfURL:yourURL encoding:NSUTF8StringEncoding error:NULL];

在您的代码中注释了使用此行的行。