Making stringWithContentsOfURL asynchronous - Is it safe?

一曲冷凌霜 提交于 2019-11-29 07:10:55

That should be safe, but why reinvent the wheel?

NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    // etc
}];

You can also use:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{
        NSError *error = nil;
        NSString *searchResultString = [NSString stringWithContentsOfURL:[NSURL URLWithString:searchURL]
                                                           encoding:NSUTF8StringEncoding
                                                              error:&error];
        if (error != nil) {
            completionBlock(term,nil,error);
        }
        else
        {
            // Parse the JSON Response
            NSData *jsonData = [searchResultString dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *searchResultsDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                              options:kNilOptions
                                                                                error:&error];
            if(error != nil)
            {
                completionBlock(term,nil,error);
            }
            else
            {

                //Other Work here
            }
        }
    });

But yes, it should be safe. I've been told though to use NSURLConnection instead due to error calls and such when communicating via the internet. I'm still doing research into this.

-(void)loadappdetails:(NSString*)appid {
    NSString* searchurl = [@"https://itunes.apple.com/lookup?id=" stringByAppendingString:appid];

    [self performSelectorInBackground:@selector(asyncload:) withObject:searchurl];

}
-(void)asyncload:(NSString*)searchurl {
    NSURL* url = [NSURL URLWithString:searchurl];
    NSError* error = nil;
    NSString* str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
    if (error != nil) {
        NSLog(@"Error: %@", error);
    }
    NSLog(@"str: %@", str);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!