NSURL始终为null

时间:2014-02-15 08:18:55

标签: ios iphone nsurlconnection nsurl nsurlrequest

我有一个方法,我调用api并返回一个像这样的字符串

     -(NSString *)urlReturn{

          NSURL *aUrl = [NSURL URLWithString:@"http://deluxecms.net/dev/api/index.php"];
         NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
        cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];
          [request setHTTPMethod:@"POST"];
          NSString *postString =    @"method=getDocument&
         deviceId=cdad86b3d8bca5c09885af94990eda193c40ab03& 
      cipher=803ae952ff4a785588397362860d045e&
      version=1&lastSync=0";
        NSLog(@"postString %@",postString);
       [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

       NSHTTPURLResponse* urlResponse = nil;
       NSError *error = [[NSError alloc] init];
       NSData *responseData = [NSURLConnection sendSynchronousRequest:request
       returningResponse:&urlResponse error:&error];

    if(error.domain!=nil)
     {
        NSString *errorDesc=[[error userInfo] objectForKey:@"NSLocalizedDescription"];
         NSLog(@"Response Error === %@",errorDesc);
        return nil;
     }

        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData
                                                       options:0 error:&error];
     if (doc == nil) {
        return nil;
     }

      NSArray *partyMembers = [doc nodesForXPath:@"//assets/asset[11]/file" error:nil];
      NSLog(@"ASSTES %@",partyMembers);
        NSString *urlStringmine;
        GDataXMLElement *urlElement = (GDataXMLElement *)[partyMembers objectAtIndex:0];
        urlStringmine = urlElement.stringValue;
        NSLog(@"MY URL STRING %@",urlString);

        return urlStringmine;
    }


    - (void)viewDidLoad
   {
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
     urlString = [self urlReturn];
       NSURL *urlPattern = [[NSURL alloc]initWithString:urlString];
       UIImage *image = [UIImage imageWithData: [NSData
      dataWithContentsOfURL:urlPattern]];
     NSLog(@"Imge %@",urlPattern);
     [self.imageView setImage:image];
  }

然后在viewDidLoad方法中我从这个字符串创建一个url,最后制作一个图像  来自此网址

但是当我打印urlString时,我得到了这样的确切值       http://deluxecms.net/dev/resource/document/Shop/Deluxe screenshot.JPG 但是当我打印urlPattern时,它总是为空。

我无法理解这种行为? 请帮帮我。

2 个答案:

答案 0 :(得分:2)

在使用之前尝试使用转义字符串:

urlString = [[self urlReturn] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

答案 1 :(得分:0)

来自initWithString:NSURL文档

  

使用URLString初始化的NSURL对象。如果URL字符串是   格式错误,返回无。

应该是一个很好的线索,网址搞砸了。用%20替换此空格,它将起作用。

简而言之,请执行此操作:

NSString *urlString = @"http://deluxecms.net/dev/resource/document/Shop/Deluxe screenshot.JPG";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
NSURL *urlPattern = [NSURL URLWithString:urlString];
NSLog(@"%@", urlPattern);