-(void)downloadImageWithURL:(NSString *)URL_str { //判斷傳入URL是否爲NSString類型 if (![URL_str isKindOfClass:[NSString class]]) { return; } UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; NSLog(@"url_str is %@",URL_str); //去掉空格,並給str進行UTF8編碼 URL_str = [[URL_str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //NSString to NSURL NSURL *url = [NSURL URLWithString:URL_str]; NSLog(@"NSURL is %@",url); dispatch_queue_t downloadQueue = dispatch_queue_create("paper image downloader", NULL); dispatch_async(downloadQueue, ^{ NSData *imageData = [NSData dataWithContentsOfURL:url]; NSLog(@"image data is %d",[imageData length]); dispatch_async(dispatch_get_main_queue(), ^{ if (imageData) { [button setImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal]; } }); }); //必定要release! dispatch_release(downloadQueue); [self.view addSubview:button]; }