Swift and Facebook SDK 4, Graph API - swift

Trying to put Facebook integration into a trial app I'm working on and can't seem to find an efficient way to make a friends list with a small profile pic from fb beside them. everything works flawless but the lengthy wait times on the data fetch. Please help with anything that will speed up image fetch times. Currently it takes about 10 seconds to fetch.
func facebookProfilePicRequest(){
let graphConnection = FBSDKGraphRequestConnection()
for result in self.facebookFriends {
if let resultingId = result["id"] as? String{
let profilePicRequest = FBSDKGraphRequest(graphPath: "/\(resultingId)/picture?redirect=false", parameters: nil)
graphConnection.addRequest(profilePicRequest){
(connection:FBSDKGraphRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
if(error != nil){
if error.code == 1009{
println("No Internet Connection, \(error.code))")
}
}else{
if let data: NSDictionary = result as? NSDictionary{
if let urlDictionary: NSDictionary = data["data"] as? NSDictionary{
if let urlString: NSString = urlDictionary["url"] as? NSString{
let url: NSURL = NSURL(string: urlString as String)!
var request1: NSURLRequest = NSURLRequest(URL: url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if error == nil{
self.facebookFriendsImages.append(data)
self.tableView.reloadData()
}
})
}
}
}
}
}
}
}
graphConnection.start()
}

Instead of fetching all the images by yourself, you could use Facebook provided FBSDKProfilePictureView. You only have to set the user profile ID, and it would load the picture for you.
This should improve things as it doesn't have to wait for all the images to be loaded before showing them, and it also load them asynchronously as you scroll the tableview.

Related

Facebook Graph API: Swift SDK not working: GraphRequest

I've been trying to follow Facebooks documentation exactly but can't understand why my code doesn't work, even though it is exactly as in the docs. I am already signing into Facebook on my app, but I need to get the profile data.
Here is my function.
func fetchFacebookUser() {
let connection = GraphRequestConnection()
connection.add(GraphRequest(graphPath: "/me")) { httpResponse, result in
switch result {
case .success(let response):
print("Graph Request Succeeded: \(response)")
case .failed(let error):
print("Graph Request Failed: \(error)")
}
}
connection.start()
}
You'll notice it is exactly like the documentation:
https://developers.facebook.com/docs/swift/graph
But I can't even build the project because I get this error in Xcode:
Contextual closure type '(GraphRequestConnection?, Any?, Error?) -> Void' expects 3 arguments, but 2 were used in closure body
Insert ',<#arg#> '
It has the 'Fix' button but that just breaks the whole thing and Xcode (red warning) complains that none of the cases in the switch statement exist.
I have searched everywhere, the closest solution I got was this SO post: Facebook GraphRequest for Swift 5 and Facebook SDK 5
But that had no answers :(
I'm sure someone has called the Graph API using Swift? What am I missing here?
However i implement facebook login my app which works fine.
On button click I called facebook login using LoginManager.
#IBAction func continueWithFacebook(_ sender: Any) {
let fbLoginManager : LoginManager = LoginManager()
fbLoginManager.logIn(permissions: ["email"], from: self) { (result, error) -> Void in
if (error == nil){
let fbloginresult : LoginManagerLoginResult = result!
if (result?.isCancelled)!{
return
}
if(fbloginresult.grantedPermissions.contains("email")) {
self.getFBUserData()
}
}
}
}
After that I get the data of user using GraphAP
func getFBUserData() {
if((AccessToken.current) != nil){
GraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
guard let userDict = result as? [String:Any] else {
return
}
if let picture = userDict["picture"] as? [String:Any] ,
let imgData = picture["data"] as? [String:Any] ,
let imgUrl = imgData["url"] as? String {
self.uURLString = imgUrl
/*let url = URL(string: imgUrl)*/
print(imgData)
}
if let n = userDict["name"] as? String {
self.name = n
}
if let e = userDict["email"] as? String {
self.email = e
}
self.socialLogIn()
}
})
}
}
Add in your pod file -
pod 'FBSDKCoreKit' and
pod 'FBSDKLoginKit'
Try using like this you will get your derided result.
Happy Coding

How to prevent an app crash or freeze due to a slow connection when retrieving a remote photo in Swift?

I want to display avatar image in my table view cell by the url string. and it will crash when the phone is not connect to the internet, so I added Reachability swift to it. but now I face another problem, when the user leaving the wifi zone or the internet connection is not stable, the app will freeze, I'm not able to tap anything until I walk back the strong wifi zone. why?
let imageData:NSData = try! NSData(contentsOf: imageUrl)
this code will crash so I try add do & catch but still not working. is it because the app can't connect to the url string and get the data so that the app will be freeze? how to prevent an app crash or freeze due to a slow connection when retrieving a remote photo?
if Reachability.shared.isConnectedToNetwork(){
if let crew = user!["crew"] as? [String:Any], let crewAva = crew["crew_avatar"] as? String {
let imageUrlString = crewAva
let imageUrl:URL = URL(string: imageUrlString)!
DispatchQueue.main.async(execute: {
do{
let imageData:NSData = try NSData(contentsOf: imageUrl)
let image = UIImage(data: imageData as Data)
self.avaImg.image = image
}
catch{
print("error")
}
})
}
}else{
print("Not reachable")
}
From the NSData documentation:
init?(contentsOf url: URL)
Important
Don't use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.
Instead, for non-file URLs, consider using the dataTask(with:completionHandler:) method of the NSURLSession class. See URL Session Programming Guide for details.
Solution
func getDataFromUrl(url: URL, completion: #escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url) { data, response, error in
completion(data, response, error)
}.resume()
}
func downloadImage(url: URL) {
getDataFromUrl(url: url) { data, response, error in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
DispatchQueue.main.async() {
self.avaImg.image = UIImage(data: data)
}
}
}
override func viewWillAppear(_ animated: Bool) {
if let crew = user!["crew"] as? [String:Any], let crewAva = crew["crew_avatar"] as? String {
let imageUrlString = crewAva
let url = URL(string: imageUrlString)!
downloadImage(url: url)
}
}
Try only updating the UI on the main thread.
if Reachability.shared.isConnectedToNetwork(){
if let crew = user!["crew"] as? [String:Any], let crewAva = crew["crew_avatar"] as? String {
let imageUrlString = crewAva
let imageUrl:URL = URL(string: imageUrlString)!
let imageData:NSData = try NSData(contentsOf: imageUrl)
let image = UIImage(data: imageData as Data)
DispatchQueue.main.async(execute: {
do{
self.avaImg.image = image
}
catch{
print("error")
}
})
}
}else{
print("Not reachable")
}

Get Facebook profile picture from URL

I want to upload the profile picture from Facebook to Firebase. I tried this answer: Upload Facebook image URL to Firebase Storage
However, Swift is giving me errors on the third line of code of that answer. The code is:
let dictionary = result as? NSDictionary
let data = dictionary?.object(forKey: "data")
let urlPic = (data?.objectForKey("url"))! as! String
Swift is telling me: Cannot call value of non-function type 'Any?!' after I changed the code to what Swift keeps suggesting me:
let urlPic = ((data as AnyObject).object(ForKey: "url"))! as! String
What is the code to use when I want to retrieve the profile picture from Facebook? My goal is to also store it into Firebase, but that will come after I get the profile picture first.
The answer is in Swift 1.2
I took reference here and implemented also
You can do this:
// accessToken is your Facebook id
func returnUserProfileImage(accessToken: NSString)
{
var userID = accessToken as NSString
var facebookProfileUrl = NSURL(string: "http://graph.facebook.com/\(userID)/picture?type=large")
if let data = NSData(contentsOfURL: facebookProfileUrl!) {
imageProfile.image = UIImage(data: data)
}
}
This is the way I got Facebook id:
func returnUserData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
println("Error: \(error)")
}
else
{
println("fetched user: \(result)")
if let id: NSString = result.valueForKey("id") as? NSString {
println("ID is: \(id)")
self.returnUserProfileImage(id)
} else {
println("ID es null")
}
}
})
}

Download high resolution profile image Facebook Graph API

Using Swift 3.0, I can download the current users image using this graph call function:
fileprivate func getCurrenUserHighResImageURL() -> String? {
var photoURLOutput : String?
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "picture.type(large)"])
graphRequest.start(completionHandler: { connection, result , error -> Void in
if ((error) != nil) {
print("Error: \(error)")
} else {
let castedResult = result as? [String : AnyObject]
if let castedResult = castedResult {
if let photURL = castedResult["picture"] as? [String : AnyObject] {
let photoData = photURL["data"] as? [String : AnyObject]
photoURLOutput = photoData?["url"] as? String
if let photoURLOutput = photoURLOutput {
CURRENT_USER_URL.updateChildValues(["highResImageURL" : "\(photoURLOutput)"])
}
}
}
}
})
return photoURLOutput
}
However this only returns a 200 x 200 pixel image. Is there any way to make a graph call to to a higher resolution?
Ive seen people making calls to the graph API using a URL like this: https://graph.facebook.com/userId/picture?width=640&height=640
as mentioned in this post : Facebook Graph Profile Picture Link
But when i attempt to download an image from that URL...
func loadUserImage(fromURL urlString:String?) {
if urlString != nil {
let imgURL: URL = URL(string: urlString!)!
let request: URLRequest = URLRequest(url: imgURL)
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) -> Void in
if (error == nil && data != nil) {
func display_image() {
let userImage = UIImage(data: data!)
self.userImage.image = userImage
}
DispatchQueue.main.async(execute: display_image)
}
})
task.resume()
}
}
there is no image to be found. (I know this function works because it works on all other images). When I type the link into my browser directly it get a JSON error back saying i don't have authorization.
Has anyone had any luck make a graph call like this? Is there some syntax I have overlooked which will return a higher res profile image?
This is what I have to request 200x200 on an iPhone 7 and 300x300 on a plus size. However I don't think you get an image back with those exact sizes. It might be slightly larger.
let deviceScale = Int(UIScreen.main.scale)
let width = 100 * deviceScale
let height = 100 * deviceScale
let parameters = ["fields": "first_name, last_name, picture.width(\(width)).height(\(height))"]
In summary, the syntax for the param to request a 400x400 would be picture.width(400).height(400).

Making multiple asynchronous HTTP requests in succession and writing with Realm

I'm currently using Alamofire for requesting data and writing to disk with Realm. Specifically, I am fetching 24 source URLS from a Facebook Graph GET request and then making 24 separate requests to retrieve the data for each image. Once the data is retrieved, I am writing to disk with Realm.
here is how I am fetching the 24 sources:
FBAPI
Alamofire.request(.GET, FBPath.photos, parameters: params).responseJSON { response in
guard response.result.error == nil else {
print("error calling GET on \(FBPath.photos)")
print(response.result.error!)
completion(latestDate: nil, photosCount: 0, error: response.result.error)
return
}
if let value = response.result.value {
let json = JSON(value)
if let photos = json[FBResult.data].array {
for result in photos {
let manager = PTWPhotoManager()
manager.downloadAndSaveJsonData(result)
}
As you can see, I have a for loop iterating through each JSON containing the source url for the photo's image in which I then make another network request for each url, like so:
Manager
func downloadAndSaveJsonData(photoJSON : JSON) {
let source = photoJSON[FBResult.source].string
let id = photoJSON[FBResult.id].string
let created_time = photoJSON[FBResult.date.createdTime].string
let imageURL = NSURL(string: source!)
print("image requested")
Alamofire.request(.GET, imageURL!).response() {
(request, response, data, error) in
if (error != nil) {
print(error?.localizedDescription)
}
else {
print("image response")
let photo = PTWPhoto()
photo.id = id
photo.sourceURL = source
photo.imageData = data
photo.createdTime = photo.createdTimeAsDate(created_time!)
let realm = try! Realm()
try! realm.write {
realm.add(photo)
}
print("photo saved")
}
}
}
There seems to be a very long delay between when each image's data is requested and when I receive a response, and it also does not appear to be asynchronous. Is this a threading issue or is there a more efficient way to request an array of data like this? It should also be noted that I am making this network request from the Apple Watch itself.
These requests will happen mostly asynchronous as you wish. But there is some synchronization happening, you might been not aware of:
The response closures for Alamofire are dispatched to the main thread. So your network responses competes against any UI updates you do.
Realm write transactions are synchronous and exclusive, which is enforced via locks which will block the thread where they are executed on.
In combination this both means that you will block the main thread as long as the network requests succeed and keep coming, which would also render your app unresponsive.
I'd recommend a different attempt. You can use GCD's dispatch groups to synchronize different asynchronous tasks.
In the example below, the objects are all kept in memory until they are all downloaded.
A further improvement could it be to write the downloaded data onto disk instead and store just the path to the file in the Realm object. (There are plenty of image caching libraries, which can easily assist you with that.)
If you choose a path, which depends only on the fields of PWTPhoto (or properties of the data, you can get through a quick HEAD request), then you can check first whether this path exists already locally before downloading the file again. By doing that you save traffic when updating the photos or when not all photos could been successfully downloaded on the first attempt. (e.g. app is force-closed by the user, crashed, device is shutdown)
class PTWPhotoManager {
static func downloadAllPhotos(params: [String : AnyObject], completion: (latestDate: NSDate?, photosCount: NSUInteger, error: NSError?)) {
Alamofire.request(.GET, FBPath.photos, parameters: params).responseJSON { response in
guard response.result.error == nil else {
print("error calling GET on \(FBPath.photos)")
print(response.result.error!)
completion(latestDate: nil, photosCount: 0, error: response.result.error)
return
}
if let value = response.result.value {
let json = JSON(value)
if let photos = json[FBResult.data].array {
let group = dispatch_group_create()
var persistablePhotos = [PTWPhoto](capacity: photos.count)
let manager = PTWPhotoManager()
for result in photos {
dispatch_group_enter(group)
let request = manager.downloadAndSaveJsonData(result) { photo, error in
if let photo = photo {
persistablePhotos.add(photo)
dispatch_group_leave(group)
} else {
completion(latestDate: nil, photosCount: 0, error: error!)
}
}
}
dispatch_group_notify(group, dispatch_get_main_queue()) {
let realm = try! Realm()
try! realm.write {
realm.add(persistablePhotos)
}
let latestDate = …
completion(latestDate: latestDate, photosCount: persistablePhotos.count, error: nil)
}
}
}
}
}
func downloadAndSaveJsonData(photoJSON: JSON, completion: (PTWPhoto?, NSError?) -> ()) -> Alamofire.Request {
let source = photoJSON[FBResult.source].string
let id = photoJSON[FBResult.id].string
let created_time = photoJSON[FBResult.date.createdTime].string
let imageURL = NSURL(string: source!)
print("image requested")
Alamofire.request(.GET, imageURL!).response() { (request, response, data, error) in
if let error = error {
print(error.localizedDescription)
completion(nil, error)
} else {
print("image response")
let photo = PTWPhoto()
photo.id = id
photo.sourceURL = source
photo.imageData = data
photo.createdTime = photo.createdTimeAsDate(created_time!)
completion(photo, nil)
}
}
}
}