如何使用iOS中的URL获取图像

时间:2014-10-28 03:06:46

标签: ios objective-c asynchronous

我有一个UIView,我试图从URL中获取一些数据,如下所示,

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat: @"www.url";
    // Create a NSURLRequest with the given URL
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                           timeoutInterval:30.0];
        [request setValue:@"03f0d561-e173-4296-ab07-0ba301ca56bb" forHTTPHeaderField:@"token"];

        // Get the data
        NSURLResponse *response = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
        // Now create a NSDictionary from the JSON data
        if (data != nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];


                jsonDataDictionary = [[jsonDictionary objectForKey:@"data"] objectAtIndex:0];

            });
        }
    });

当我运行此代码时,图像是黑色的。图像没有加载。谁能帮我这个。

提前致谢!

3 个答案:

答案 0 :(得分:0)

我使用SDWebImageAFNetworking,比NSMutableURLRequest更容易。

答案 1 :(得分:0)

您发布的代码存在许多问题。首先,您应该使用

  + (void)sendAsynchronousRequest:(NSURLRequest *)request
                            queue:(NSOperationQueue *)queue
                completionHandler:(void (^)(NSURLResponse *response,
                                    NSData *data,
                NSError *connectionError))handler

而不是使用主线程的同步请求。 Anywho,问题源于您处理数据的方式。您正尝试使用NSJSONSerialization解析它。这不是JSON。这是图像数据(大概是.png或.jpg)。

您需要使用

+ (UIImage *)imageWithData:(NSData *)data

如果仍然无效,请将网址粘贴到浏览器中并查看其类型

答案 2 :(得分:0)

您可以使用url轻松获取图像。如果您执行以下代码,则可以轻松获取该图像。

这里非常重要的是从服务器获取图像时

  -> First you have to convert to NSData

  -> After that you have to convert to image.

编码部分

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL     URLWithString:@"http://www.url"]];

    [request setHTTPMethod:@"GET"];

    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];

    NSError *err;

    NSURLResponse *response;

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request   returningResponse:&response error:&err];

    //You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER in Google.If you do this clearly you can get the correct results.

    //After that it depends upon the json format whether it is DICTIONARY or ARRAY 

    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];

    //Now if you have IMAGE URL in Dictionary

    //Also you can use valueForKey instead of objectForKey for getting images from server

    NSString *stringImage = [NSString stringWithFormat:@"%@",[jsonDict objectForKey:@"Data"]objectForKey:@"ImageURL"];

                   OR
     //Now if you have image URL in Array of Dictionary

    NSMutableArray *array = [jsonDict objectForKey:@"Data"];

    for(int i=0;i<[array count];i++)
    {

        NSString *stringImage = [NSString stringWithFormat:@"%@",[[array objectAtIndex:i]objectForKey:@"ImageURL"]];

    }

    // Now Convert into Data from String

     NSData *data = [NSData dataWithContentsOfURL:[NSURL urlWithString:stringImage]];

    // Now convert into Image from Data

    yourImageView.image = [UIImage imageWithData:data];