后台请求案例CATransaction错误

时间:2014-11-19 16:16:09

标签: ios uiimage background-image nsurlconnection background-process

我正在尝试在后台下载图片。当我尝试下载它时,我收到下一个错误:

在事务

中调用的

+ [CATransaction synchronize]

我正在尝试在UITableView的cellForRowAtIndexPath中下载它。我第一次遇到这样的问题。提前致谢。这是代码,它位于单独的文件中:

- (id) initWithImageID: (NSString*) imageID
{
    self = [super init];

    if (self)
    {
        self.receivedData = [NSMutableData data];
        self.imageID = imageID;

        NotedPreferences* np = [NotedPreferences sharedPreferences];
        NSString* url = [[np apiURL] stringByAppendingFormat: @"/thumbs/%@.jpg", imageID];
        NSURL* imageURL = [NSURL URLWithString: url];

        NSMutableURLRequest *theRequest = (NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:imageURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeout60];
        [self basicAuthForRequest:theRequest withUsername:@"app" andPassword:@"123"];
        self.theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
        CFRunLoopRun();
    }

    return self;
}

- (void)basicAuthForRequest:(NSMutableURLRequest *)request withUsername:(NSString *)username andPassword:(NSString *)password
{
    CFStringRef usernameRef = (__bridge CFStringRef)username;
    CFStringRef passwordRef = (__bridge CFStringRef)password;

    CFHTTPMessageRef authoriztionMessageRef = CFHTTPMessageCreateRequest(kCFAllocatorDefault,    (__bridge CFStringRef)[request HTTPMethod], (__bridge CFURLRef)[request URL], kCFHTTPVersion1_1);

    CFHTTPMessageAddAuthentication(authoriztionMessageRef, nil, usernameRef, passwordRef, kCFHTTPAuthenticationSchemeBasic, FALSE);

    CFStringRef authorizationStringRef = CFHTTPMessageCopyHeaderFieldValue(authoriztionMessageRef, CFSTR("Authorization"));

    [request setValue:(__bridge NSString *)authorizationStringRef forHTTPHeaderField:@"Authorization"];

    CFRelease(authorizationStringRef);
    CFRelease(authoriztionMessageRef);
}

- (void)connection: (NSURLConnection *) connection didReceiveData: (NSData *) data
{
    [self.receivedData appendData: data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (self.receivedData != nil)
    {
        UIImage* image = [UIImage imageWithData: self.receivedData];

        if ([self.delegate respondsToSelector:@selector(requestHaveFinishedWithImage:imageID:success:)])
            [self.delegate requestHaveFinishedWithImage:image imageID:self.imageID success: true];
    }

    CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void)connection: (NSURLConnection *) connection didFailWithError: (NSError *) error
{
    if ([self.delegate respondsToSelector:@selector(requestHaveFinishedWithImage:imageID:success:)])
        [self.delegate requestHaveFinishedWithImage:nil imageID:self.imageID success: false];

    CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void) dealloc
{
    NSLog(@"dealloc of DownloadImageObject");
}

0 个答案:

没有答案