【问题标题】:NSURLConnection and NSURLConnectionDelegate work on different threadNSURLConnection 和 NSURLConnectionDelegate 在不同的线程上工作
【发布时间】:2012-07-03 05:22:27
【问题描述】:

如标题所述,我做了一些这样的 NSURLConnection。但是我发现委托方法无法运行。任何人都知道如何处理它?

编辑: 我的委托在主线程上工作,而 NSURLConnection 在操作队列上工作。现在的情况是 :NSURLConnection 工作正常,但委托不会运行。

编辑 2: 我使用了类方法 [NSURLConnection connectionWithRequest: delegate:]

这是我的主队列

 NSOperationQueue *queuePhoto = [[NSOperationQueue alloc] init];
 NSInvocationOperation *invocationOperationPhotos = [[NSInvocationOperation alloc] initWithTarget:self   selector:@selector(transferToServerAddimages:) object:arrayOfASection]; 
//                        [invocationOperationPhotos addObserver:self forKeyPath:@"isExecuting" options:0 context:invocationOperationPhotos];
 //                        [invocationOperationPhotos addObserver:self forKeyPath:@"isCancelled" options:0 context:invocationOperationPhotos];
//                        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(<#selector#>) name:@"isExecuting" object:nil];
                        [invocationOperationPhotos setQueuePriority:NSOperationQueuePriorityHigh];
                    [queuePhoto addOperation:invocationOperationPhotos];
                    [mutableArrayPhotoQueue addObject:queuePhoto];
                    [invocationOperationPhotos release];
                    [queuePhoto release];

这是我的 NSURLConnnection:

- (void) transferToServerAddimages:(NSArray *) arrayToAdd
{
NSLog(@"[NSOperationQueue currentQueue]: %@", [NSOperationQueue currentQueue]);

NSString *murphoAppPrefix = [[AppDelegate sharedAppDelegate] murphoAppPrefix];
// setting up the request object now
NSString *urlString = [murphoAppPrefix stringByAppendingString:@"addPhotos.php"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

/*
 add some header info now
 we always need a boundary when we post a file
 also we need to set the content type
 */
// set header value ,   some random text that will never occur in the body
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

/*
 now lets create the body of the post
 */
NSMutableData *body = [NSMutableData data];

//  email part    
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"email\"\r\n\r\n%@", self.trip.whoCreate.email] dataUsingEncoding:NSUTF8StringEncoding]];

//  password part
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"password\"\r\n\r\n%@", self.trip.whoCreate.psw] dataUsingEncoding:NSUTF8StringEncoding]];

//  image part
NSInteger subCount=0;
for (NSDictionary *aDict in arrayToAdd) {
    //  belonging part

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"r_whichShortTrip%d\"\r\n\r\n%@", subCount, [aDict objectForKey:@"r_whichShortTrip"]] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uniqueId%d\"\r\n\r\n%@", subCount, [aDict objectForKey:@"uniqueId"]] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"createdTime%d\"\r\n\r\n%@", subCount, [aDict objectForKey:@"createdTime"]] dataUsingEncoding:NSUTF8StringEncoding]];

    UIImage *imageFile = [aDict objectForKey:@"image"];
    NSData *imageData = UIImageJPEGRepresentation(imageFile, 1.0);
    NSString *imageName = [[URLConnect createUUID] stringByAppendingString:@".jpg"];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
    [body appendData:[[NSString stringWithFormat: 
                       @"Content-Disposition: form-data; name=\"image%d\"; filename=%@\r\n", subCount, imageName]                          dataUsingEncoding:NSUTF8StringEncoding]];  
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    UIImage *thumbnail = [aDict objectForKey:@"thumbnail"];
    NSData *thumbnailData = [NSData dataWithData:UIImageJPEGRepresentation(thumbnail, 1)];
    NSString *thumbnailName = [[URLConnect createUUID] stringByAppendingString:@".jpg"];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
    [body appendData:[[NSString stringWithFormat: 
                       @"Content-Disposition: form-data; name=\"thumbnail%d\"; filename=%@\r\n", subCount++, thumbnailName]                          dataUsingEncoding:NSUTF8StringEncoding]];  
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:thumbnailData]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}


[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];

// now lets make the connection to the web
[NSURLConnection connectionWithRequest:request delegate:self];

}

这是我的代表:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [[[AppDelegate sharedAppDelegate] mArrayOfFailedConnection] addObject:connection];
     [connection cancel];
     connection = nil;
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"response: %@", response);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connection: %@", connection);
}

【问题讨论】:

  • 如果您的线程没有运行循环,则 NSURLConnection 将无法工作。
  • 你添加了这一行 [connection startConnection];
  • @Kevin Ballard,正如刚才编辑的那样,委托在主线程上并且不会工作,而不是 NSURLConnection。
  • @Arundhati,我使用了类方法[NSURLConnection connectionWithRequest: delegate:]
  • @Anna 你必须在带有运行循环的线程上启动连接。然后将在该线程上调用委托方法。连接 IO 本身总是发生在 Foundation 管理的另一个线程上。

标签: iphone ios nsurlconnection nsurlconnectiondelegate


【解决方案1】:

实际上,当您将操作选择器设置为“transferToServerAddimages”时,这意味着当此函数完全执行时,您的操作将完成,同样因为 NSUrlConnection 在启动它的同一线程上调用其委托,因此很可能是该线程(OperationQueue) 在响应到达之前完成。如果你确实想使用 NSOperationQueue,那么更好的函数是 NSUrlConnection 的“sendAsynchronousRequest:queue:completionHandler:”。

【讨论】:

    【解决方案2】:

    代表是什么,NSOperation?一种可能性是您的操作正在调用-[connectionWithRequest:delegate:] 并退出,这会导致它完成并被删除。在操作的 dealloc 中放入NSLog 以查看其是否正在运行。

    假设所有操作都是NSURLConnection 事务,您不需要将事务包装在NSOperation 中以获得并发,因为这些事务已经是异步的。但是,如果您真的想使用NSOperation(出于协调目的等),请将其设为“并发”并将其放在主队列中。那些比较棘手,但周围有例子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多