如何格式化IOS中的字符串(@“url”)

时间:2013-12-23 17:27:08

标签: ios objective-c string-formatting

我收到来自网络服务的回复,回复基于逗号分隔的URl

NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"ResponseData: %@", str);

它的输出就像

ResponseData: http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-00-12-46.jpg,http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-01-12-32.jpg

我想将响应传递给我的图片库,其中包含以下格式的网址

networkImages = [[NSArray alloc] initWithObjects:@"http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-00-12-46.jpg",@"http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-01-12-32.jpg",nil];

如何格式化我对@"URL",@"URL"的回复,以便将其存储到某个变量e,g; abc并将其传递给

networkImages = [[NSArray alloc] initWithObjects:abc,nil];

2 个答案:

答案 0 :(得分:0)

NSString有一个方法componentsSeparatedByString:就是这样做的。

networkImages = [str componentsSeparatedByString:@","];

答案 1 :(得分:0)

我认为你有两种方式:

第一种方式; (我已在我的新闻App中使用) *您必须使用JSON结果。 *如果您需要,可以使用SBJsonParserSDWebImage

NSError *myError = nil;
NSString *link = [NSString stringWithFormat:@"http://www.myexamplenews.com/mobil-app.php?q=imageList&id=%i",galleryId];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:link] cachePolicy:0 timeoutInterval:5];
NSURLResponse *response=nil;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&myError];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:nil];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];     
if (myError == nil)
{
    NSArray *jsonGalleryDetail = [jsonParser objectWithString:jsonString];
    jsonParser = nil;
    GalleryDetailView *view = [[GalleryDetailView alloc] initWithFrame:[[UIScreen mainScreen] andImageList: jsonGalleryDetail];
    [self.navigationController pushViewController:GalleryDetailView animated:YES];
}

GalleryDetailView.h

@interface GalleryDetailView : UIView
{
}
- (id)initWithFrame:(CGRect)frame andImageList:(NSArray *)myList;
@end

GalleryDetailView.m

@implementation GalleryDetailView

- (id)initWithFrame:(CGRect)frame andImageList:(NSArray *) myList;  
{
  self = [super initWithFrame:frame];
  if (self)
  {
     //Your code here
     for (NSString *str in myList)
     {
           NSURL *imageURL = [NSURL URLWithString:str];
           //This is SDWebImage extension. 
           UIImage *image = [UIImage setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
     }
  }
  return self;
}
@end

第二种方式;

NSArray *arr = [ResponseData componentsSeparatedByString:@","];
GalleryDetailView *view = [[GalleryDetailView alloc] initWithFrame:[[UIScreen mainScreen] andImageList: arr];
    [self.navigationController pushViewController:GalleryDetailView animated:YES];

我更喜欢使用JSON数据。它是由你决定。我希望这些信息对您有所帮助。