Getting Twitter profile image with Parse in Swift
AHere is the Swift version. I had to change the username from Parse to screenName from PFTwitter, and added a line to get the highest resolution version of the picture. Note that as I'm using this to populate a sign up screen after logging in, this will test for the app account being connected to a Twitter account. Most probably this would work even if the link has been added after account creation, too.
if PFTwitterUtils.isLinkedWithUser(PFUser.currentUser()!) {
let screenName = PFTwitterUtils.twitter()?.screenName!
let requestString = ("https://api.twitter.com/1.1/users/show.json?screen_name=" + screenName!)
let verify: NSURL = NSURL(string: requestString)!
let request: NSMutableURLRequest = NSMutableURLRequest(URL: verify)
PFTwitterUtils.twitter()?.signRequest(request)
var response: NSURLResponse?
var error: NSError?
let data: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)!
if error == nil {
let result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error)
let names: String! = result?.objectForKey("name") as! String
let separatedNames: [String] = names.componentsSeparatedByString(" ")
self.firstName = separatedNames.first!
self.lastName = separatedNames.last!
let urlString = result?.objectForKey("profile_image_url_https") as! String
let hiResUrlString = urlString.stringByReplacingOccurrencesOfString("_normal", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
let twitterPhotoUrl = NSURL(string: hiResUrlString)
let imageData = NSData(contentsOfURL: twitterPhotoUrl!)
let twitterImage: UIImage! = UIImage(data:imageData!)
}
You probably want to add something like this to prepare a PFFile to save to your new user, too!
let cgImage = twitterImage.CGImage
let bitsPerComponent = CGImageGetBitsPerComponent(cgImage)
let bytesPerRow = CGImageGetBytesPerRow(cgImage)
let colorSpace = CGImageGetColorSpace(cgImage)
let bitmapInfo = CGImageGetBitmapInfo(cgImage)
let context = CGBitmapContextCreate(nil, 300, 300, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)
CGContextSetInterpolationQuality(context, kCGInterpolationHigh)
CGContextDrawImage(context, CGRect(origin: CGPointZero, size: CGSize(width: CGFloat(300), height: CGFloat(300))), cgImage)
let scaledImage = UIImage(CGImage: CGBitmapContextCreateImage(context))
let imageUIImage = UIImageJPEGRepresentation(scaledImage, 0.6)
let imageFile: PFFile = PFFile(name: (PFUser.currentUser().objectId! + "profileImage.jpg"), data:imageUIImage)
Getting Twitter profile image with Parse in Swift 2
Based on your code, I was able to get the Twitter image to be retrieved using:
if PFTwitterUtils.isLinkedWithUser(PFUser.currentUser()!) {
let screenName = PFTwitterUtils.twitter()?.screenName!
let requestString = NSURL(string: "https://api.twitter.com/1.1/users/show.json?screen_name=" + screenName!)
let request = NSMutableURLRequest(URL: requestString!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
PFTwitterUtils.twitter()?.signRequest(request)
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
print(data)
print(response)
print(error)
if error == nil {
var result: AnyObject?
do {
result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
} catch let error2 as NSError? {
print("error 2 \(error2)")
}
let names: String! = result?.objectForKey("name") as! String
let separatedNames: [String] = names.componentsSeparatedByString(" ")
//self.firstName = separatedNames.first!
//self.lastName = separatedNames.last!
let urlString = result?.objectForKey("profile_image_url_https") as! String
let hiResUrlString = urlString.stringByReplacingOccurrencesOfString("_normal", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
let twitterPhotoUrl = NSURL(string: hiResUrlString)
let imageData = NSData(contentsOfURL: twitterPhotoUrl!)
let twitterImage: UIImage! = UIImage(data:imageData!)
}
}).resume()
}
I rolled the result handling into the data task and fixed the JSONObjectWithData:options:
call for Swift 2.
Twitter user image Parse - Swift
Try with below code,
if let imageData = NSData(contentsOfURL: twitterPhotoUrl!)
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.userImg.image = UIImage(image: imageData!)
})
}
Hope this will work
Getting Twitter user details using swift
You can access the username and userID of the logged-in user pretty easily. Inside most Twitter login methods you'll see something like this:
@IBAction func loginTwitter(sender: UIBarButtonItem) {
Twitter.sharedInstance().logInWithCompletion {
(session, error) -> Void in
if (session != nil) {
print(session?.userName)
print(session?.userID)
} else {
print("error")
}
}
}
Twitter does not expose the email address of users as far as I'm aware.
For the profile image you'll need to send a GET request. Here is some code that may not be up to date with the latest TwitterKit version but should at least give you a sense of how the request should be formatted.
func getUserInfo(screenName : String){
if let userID = Twitter.sharedInstance().sessionStore.session()!.userID {
let client = TWTRAPIClient(userID: userID)
let url = "https://api.twitter.com/1.1/users/show.json"
let params = ["screen_name": screenName]
var clientError : NSError?
let request = Twitter.sharedInstance().APIClient.URLRequestWithMethod("GET", URL: url, parameters: params, error: &clientError)
client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
if let someData = data {
do {
let results = try NSJSONSerialization.JSONObjectWithData(someData, options: .AllowFragments) as! NSDictionary
print(results)
} catch {
}
}
}
}
}
You'll need to go through the JSON that gets returned and find "profile_image_url_https" a couple levels down.
Good Luck!
After convert my code to swift 3 Twitter not get the users profile image
This error occurs when the user name is incorrect. This should work.
let profilepic = FHSTwitterEngine.shared().getProfileImageURLString(forUsername: FHSTwitterEngine.shared().authenticatedUsername, andSize: FHSTwitterEngineImageSizeOriginal)
print("profile pic is \(profilepic)")
How to get twitter profile picture in ios?
Have you considered using a 3rd party Twitter engine for this? I've used FHSTwitterEngine with a fair amount of success, and it seems to be under active development.
To pull a profile picture you would do something like this:
[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:@"<consumer_key>" andSecret:@"<consumer_secret>"];
[[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self
withCompletion:^(BOOL success) {
if (success) {
UIImage *profileImg = [[FHSTwitterEngine sharedEngine] getProfileImageForUsername:@"<username>" andSize:size];
}
}];
Related Topics
Swift 4.2 - _Shared Attribute Near Type
Accessing Global Variable in Swift
Extending Typed Array by Conforming to a Protocol in Swift 2
Saving Swifty JSON Array to User Defaults
Passing Data from Simple Nsview to Swiftui View
Handling an Attribute of an Xml Element in Swift
Swift: Search Bar Created at Auto Focus
Swift: Can Not Use Array Filter in If Let Statement Condition
Cannot Use Tabview on Swiftui, Watchos
Is Is Possible to Use Vapor 3 Postgres Fluent in a Standalone Script
How to Use Unsafemutablepointer<Opaquepointer> in Swift
Cabasicanimation Creates Empty Default Value Copy of Calayer
Ambiguous Use of Observe Firebase Db
How to Use Navigation in Alert Using Swiftui
Storing Array of Custom Objects in Userdefaults