我正在尝试将图像上传到Parse并将其与我的共享扩展中的PFObject相关联,但是我不知道如何在编写共享扩展的约束下正确执行此操作。
我首次尝试使用PFFile和PFObject类
// Create the UserPhoto PFObject and associate with PFFile
PFObject *userPhoto = [PFObject objectWithClassName:@"UserPhoto"];
userPhoto[@"message"] = @"my photo";
NSData *imageData = UIImageJPEGRepresentation(image, 0.2);
PFFile *imageFile = [PFFile fileWithName:@"image.jpg" data:imageData];
userPhoto[@"imageFile"] = imageFile;
[userPhoto saveInBackground];
此方法的问题在于,如果在销毁应用程序扩展时saveInBackground尚未完成,则上载将终止,因此您必须使用NSURLSession根据app extension documentation使连接保持活动状态。
NSURLSession不能与Parse类一起使用,因此我必须使用Parse REST API启动照片上传,然后在上传照片后将url与对象相关联。
上传照片 - >将照片网址与对象关联
这会设置上传任务以将图像上传到Parse
// [self backroundSession] just configures a session and returns it
NSURLSession *session = [self backgroundSession];
NSURL *url = [NSURL URLWithString:@"https://api.parse.com/1/files/pic.jpg"];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
[req addValue:@"12345" forHTTPHeaderField:@"X-Parse-Application-Id"];
[req addValue:@"12345" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
[req addValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
[req setHTTPMethod:@"POST"];
// path is the location of the image to be uploaded
NSURLSessionUploadTask *myTask = [session uploadTaskWithRequest:req fromFile:[NSURL fileURLWithPath:path]];
[myTask resume];
照片上传完成后,我们必须将网址与对象关联起来。就像上面一样,我正在创建一个名为UserPhoto的对象
- (void)URLSession:(NSURLSession *)mySession task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
// note: this bg session doesn't set delegate so we only create the UserPhoto object once
NSURLSession *session = [self backgroundSessionForUserPhoto];
NSURL *url = [NSURL URLWithString:@"https://api.parse.com/1/classes/UserPhoto"];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
[req addValue:@"12345" forHTTPHeaderField:@"X-Parse-Application-Id"];
[req addValue:@"12345" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
[req addValue:[PFUser currentUser].sessionToken forHTTPHeaderField: @"X-Parse-Session-Token"];
[req addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setHTTPMethod:@"POST"];
NSDictionary *jsonDict = @{@"imageFile" : @{@"name" : response[@"url"], @"__type" : @"File"}, @"message" :@"my photo"};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted
error:&error];
if (!error) {
[req setHTTPBody:jsonData];
NSURLSessionTask *myTask = [session dataTaskWithRequest:req];
[myTask resume];
}
}
链接REST API调用有时会起作用,有时不会导致图像被上传但图像网址没有与UserPhoto关联,因此我想知道操作系统是否禁止在扩展程序被销毁后触发另一个NSURLSession。
所以这是我的问题:
1)解析是否提供了对NSURLSession的抽象,从而消除了使用Parse REST API的需要?
否则
2)如何安全地链接两个NSURLSession,以便上传图像并将图像URL与Parse对象成功关联?