如何使用 NSURLSession 保存 Facebook 个人资料图片?
Posted
技术标签:
【中文标题】如何使用 NSURLSession 保存 Facebook 个人资料图片?【英文标题】:How do I save a facebook profile picture using NSURLSession? 【发布时间】:2016-02-19 12:21:36 【问题描述】:我只是在创建一个简单的 facebook 登录应用程序,在我的 viewdidload() 方法中,我拥有权限并且我正在获取名称、用户名、电子邮件 ID 和个人资料图片链接,但我想做的是尝试下载该链接(URL)并在本地保存/下载。
刚开始使用 x-code,如有任何帮助,将不胜感激。
> - (void)viewDidLoad
>
> [super viewDidLoad];
> FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init]; loginButton.center = self.view.center; [loginButton
> setDelegate:self];
> loginButton.loginBehavior=FBSDKLoginBehaviorWeb;
> [self.view addSubview:loginButton];
> loginButton.readPermissions = @[@"public_profile",@"email",@"user_friends",@"user_about_me",@"user_friends",@"user_birthday",@"user_hometown"];
> loginButton.publishPermissions=@[@"publish_actions"];
> FBSDKLoginManagerLoginResult *result;
>
>
>
>
> if ([result.grantedPermissions containsObject:@"email"])
> NSLog(@"%@",result);
>
>
>
> NSMutableDictionary* param = [NSMutableDictionary dictionary];
> [param setValue:@"id,name,email,picture.width(100).height(100),bio"
> forKey:@"fields"];
>
>
> NSURL *profilePictureURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/user/picture?type=large"]];
> NSURLRequest *profilePictureURLRequest = [NSURLRequest requestWithURL:profilePictureURL
> cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
> // Facebook profile picture cache policy: Expires in 2 weeks
> [NSURLSession sessionWithConfiguration:profilePictureURLRequest delegate:self delegateQueue:nil];
【问题讨论】:
【参考方案1】:试试这个代码,它会将图像保存在应用程序文档目录中。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=normal",[result objectForKey:@"id"]]]];
[imageData writeToFile:[NSString stringWithFormat:@"%@/profilePic.jpg",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]] atomically:YES];
)
【讨论】:
【参考方案2】:使用您的NSURLRequest
创建一个NSURLSessionDataTask
任务:
NSURL *profilePictureURL = ...;
NSURLRequest *profilePictureURLRequest = ...;
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:profilePictureURLRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
// This block is called when the request completes / fails.
if ((!error) && (data.length > 0))
// Write to local URL on background thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^
NSURL *someFileUrl = ...;
[data writeToUrl:someFileUrl atomically:YES];
);
];
// Send the request...
[task resume];
【讨论】:
以上是关于如何使用 NSURLSession 保存 Facebook 个人资料图片?的主要内容,如果未能解决你的问题,请参考以下文章