0

我需要从 iOS6 中的 URL 获取 JSON 数据。如何将这些数据导入 iOS?如果数据中有一个图像的 URL,我该如何获取这些图像呢?

4

2 回答 2

3

解析 json 并将 url 放入 Array 或 NSString

 UIImageView *image1;
 NSString *responseString;//it will contain the url 
 image1.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:responseString]]];
于 2013-07-11T08:24:32.837 回答
0
/**
    HTTP CONSTANTS
 **/
#define TIMEOUT_INTERVAL 60
#define CONTENT_TYPE @"Content-Type"
#define URL_ENCODED @"application/x-www-form-urlencoded"
#define GET @"GET"
#define POST @"POST"

-(NSMutableURLRequest*)getNSMutableURLRequestUsingPOSTMethodWithUrl:(NSString *)url postData:(NSString*)_postData
{
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
    [req setHTTPMethod:POST];
    [req addValue:URL_ENCODED forHTTPHeaderField:CONTENT_TYPE];
    [req setHTTPBody: [_postData dataUsingEncoding:NSUTF8StringEncoding]];
    return req;
}


-(NSMutableURLRequest*)getNSMutableURLRequestUsingGetMethodWithUrl:(NSString*)url
{
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
    [req setHTTPMethod:GET];
    return req;
}


    NSString *_postData = {<Your postData>}
    NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:LOGIN_URL postData:_postData];
    [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (error)// it means server error
         {
             //error while connecting server
         }
         else
         {
             NSError *errorInJsonParsing;
             NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorInJsonParsing];
             if(errorInJsonParsing) //error parsing in json
             {
                 //error in json parsing
             }
             else
             {
                 @try
                 {
                    NSLog(@"json==%@",json);
                    // json is basically in key value format which is NSDictionary
                    // if you get the url of image inside this json, then again hit the url to get the image ( u can get the image in NSData which is declared above )
                 }
                 @catch (NSException *exception)
                 {
                     //exception
                 }

             }
         }
     }];
于 2013-07-11T08:25:10.367 回答