Post a tweet with a photo using the Swifter Framework / Library - ios

I'm using Swifter Library to try to post a tweet with a photo but every time I try, i get an error "The operation couldn’t be completed. (SwifteriOS.SwifterError error 1.)"
My code looks like
var tweetMedia: [String: Any]?
//I then set tweetMedia to a UIImageView from the UIImagePickerControllerOriginalImage
let picForTwitterApi = tweetMedia![UIImagePickerControllerOriginalImage] as! UIImage
let image = UIImagePNGRepresentation(picForTwitterApi) as Data?
self.swifter?.postTweet(status: tweetText, media: image!, inReplyToStatusID: nil, coordinate: nil, placeID: nil, displayCoordinates: nil, trimUser: false,
tweetMode: TweetMode.default, success: { json in self.alert(title: "Tweet PHOTO sent", message: "👍🏾")
}, failure: failureHandler)
But it does not work, i even tried
self.swifter?.postMedia(image!, additionalOwners: nil, success: { json in
print(json)
instead, still no success.
When I post a regular vanilla tweet like
self.swifter?.postTweet(status: tweetText, inReplyToStatusID: nil, trimUser: false, tweetMode: TweetMode.default, success: { json in
print(json).....
Everything works perfectly fine, I only have problems when I try to post a photo. Please help. Thanks in advance

I found the solution. The picture must be small. Even smaller than 5mb the documentation suggest. I used an image that was only 100KB and it worked. If I want to post a larger image/video (even just one picture) you have to use the chunked media post ability

Related

getting error when i trying to convert AVAssetURL to Data

Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_9807.MOV” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/var/mobile/Media/DCIM/109APPLE/IMG_9807.MOV, NSUnderlyingError=0x1c1e5fe00 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"
i am sending asset URL to other controller and try to convert into data
PHImageManager.default().requestAVAsset(forVideo: self.albumView.phAsset, options: options) { (video, audioMix, info) in
DispatchQueue.main.async {
let urlAsset = video as! AVURLAsset
self.dismiss(animated: false, completion: {
self.delegate?.fusumaVideoCompleted(withFileURL: urlAsset.url)
})
}
}
here below methods for convert AVAssetUrl to data
do {
let data = try Data(contentsOf: product.videoURL, options: .mappedIfSafe)
return .upload(.multipart([MultipartFormData(provider: .data(data), name: "post[video]", fileName: "video.\(pathExtension)", mimeType: "video/\(pathExtension)")]))
} catch {
debugPrint(error)
}
As the error tells you, you cannot access the video file in the user's photo library by way of its URL for purposes of uploading it. You should obtain the video data and upload that. A video is very big, so you should not get the data directly and hold it in memory; instead, export the data to a file in a place that you are allowed to access, such as the Temporary folder.
To do that, you might (for example) use this method:
https://developer.apple.com/documentation/photos/phassetresourcemanager/1616280-writedata
Or this one:
https://developer.apple.com/documentation/photos/phimagemanager/1616981-requestexportsession
If you use the Mail app to email a video from your own device's photo library, you will actually see that happening; there is a pause with a progress bar while the video is exported, and then the email is constructed.

UIImagePickerController - Save Recorded Video to Camera Roll Error

I'm trying to save a video recorded with camera using the UIImagePickerController. I've tried two different ways, and both are not working at all.
First attempt:
if let pathURL = info["UIImagePickerControllerMediaURL"] as! URL?, mediaType == kUTTypeMovie {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: pathURL)
}, completionHandler: { (isSuccessfull, error) in
if error != nil {
// ERROR
// error.localizedDescription value below
// "The operation couldn’t be completed. (Cocoa error -1.)"
} else if isSuccessfull {
// SUCCESS
}
})
}
On that attempt, I'm always getting the error "The operation couldn’t be completed. (Cocoa error -1.)"
Second attempt:
if let filePath = info["UIImagePickerControllerMediaURL"] as! NSURL,
let stringPath = filePath.path {
UISaveVideoAtPathToSavedPhotosAlbum(stringPath, self, #selector(Controller.videoSaved(videoPath:didFinishSavingWithError:contextInfo:)), nil)
}
This is not working either... The callback, the error is nil, but the video is not saved into the camera roll. Also, when I use the UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(stringPath), this method also returning me false all the time. I'm not able to understand why the video recorded would be incompatible to save.
I really don't know what I'm doing wrong. What am I missing? A configuration in plist?
Here's how look like the value of info["UIImagePickerControllerMediaURL"]:
file:///private/var/mobile/Containers/Data/Application/2B9BE04A-17B3-49CE-B4BA-C45F183E9A64/tmp/837294779101__C4825AFE-8140-420F-ACD0-64623C7A4753.MOV
For pictures taken with camera, PHPhotoLibrary method works very fine... It's only videos that is not able to be saved.
Not sure in 100% but I believe that it wasn't working for me because I was saving the video only after a request to my API was successful. My assumption is that the path URL is temporary and has a very short time of life. When I pass it to another controller, and make API call, it doesn't work. But if I save the video directly in the delegate method of UIImagePickerViewController, then it works fine.

Resize image before getting data from URL : Swift

I am presenting some photos into a collectionView. I am getting some URL's from the server and I do a request with KingFisher. My problem is that the URLs I have include images with more than 2000x1000 pixels. Can I avoid downloading such big photos and instead requesting a smaller version of that image? I don't want to download and then resize cause that will not speed things up. Thanks.
My code :
self.image.kf.setImage(with: URL(string:imageUrl)!, placeholder: UIImage(named: "placeholderImage"), options: nil, progressBlock: { receivedSize, totalSize in
print(totalSize)
}, completionHandler: nil)

How do I get larger a image from Facebook album using Graph API iOS?

I have tried several ways to get larger images from Facebook Graph API, but I have not succeeded.
I don't really know how this Parameters work. So will you explain me that too?
Also I need to know how to grab the larger images.
I first get the album I'd and then pictures ID and then I fetch the image of the album.
What is the best picture size to get for iPhone 6?
let parameters = ["fields": "picture.height(400).width(200)"]
FBSDKGraphRequest(graphPath: "/{picture-id}", parameters: parametes, HTTPMethod: "GET")
If the picture you get with picture?type=large is not big enough, I suggest you try with picture?width=9999 for example.
The code would be:
let requestPicture = FBSDKGraphRequest(graphPath: "{user_id}/picture?width=9999&redirect=false", parameters: nil, HTTPMethod: "GET")
This SO thread may be useful to you regarding parameters.
If you already have the user's ID and they have given appropriate permissions, you can do:
let imageUrl = NSURL(string: "https://graph.facebook.com/\(userId)/picture?type=large")
if let data = NSData(contentsOfURL: imageUrl!) {
let profilePicture = UIImage(data: data)
}
}
You can also do any of the enum values: small, normal, album, large, square as explained here. Better yet, you can use AFNetworking to load the image in the background with a placeholder image, which handles caching and everything for you. See here for more details, specifically setImageWithURL.
From the login or by making the basic graph request with me you can get user-id and from that user-id you may try this
You can try like this:
let fbRequest = FBSDKGraphRequest(graphPath:"/{user-id}/picture?redirect=false&type=large", parameters: nil);
fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
print("Result is : \(result)")
/* this will return the data of the image which you can use with imageview with data method {
"data": "ProfilePictureSource",
"paging": {}
}*/
} else {
println("Error Getting Friends \(error)");
}
}
For the fields which you have pass picture.height and picture.width is used to specify the image with which is return to you in the response
You can use both types of size reference :
Predefined sizes: small, normal, large, square.
Custom size: specify the width and height of the image you want
For more information you can check the facebook doc : Facebook doc:User Profile
You can use Graph API to get different size of images. You need to have picture id. You request it like this:
/{picture-id}?fields=width,height,images
Since above query returns JSON data. In that data "images" contains different sizes.

AlamofireImage: Can't get image in completion block from af_setImageWithURL

all
I am learning Swift and I am trying to set an image on a UIImageView using AlamofireImage. I am using the following code:
self.listImageView.af_setImageWithURL(
NSURL(string: list!.image!)!,
placeholderImage: nil,
filter: nil,
imageTransition: .CrossDissolve(0.5),
completion:{ image in
print(image)
}
)
and the result in the console is the following:
SUCCESS: <UIImage: 0x7fb0c3ec3d30>, {512, 286}
My objective is to do something with the image once is downloaded, but the problem is that I don't understand the signature for the completion callback and I don't know how to access to the image in the completion block. According to the documentation, is Result<UIImage, NSError>.
I guess is something really simple, but I am not realizing it.
Thanks
The image variable passed into the completion block is actually Alamofire.Response type, not the underlying UIImage instance itself that was fetched.
You need to update your completion block like below in order to get the actual image from the response:
self.listImageView.af_setImage(
withURL: URL(string: list!.image!)!,
placeholderImage: nil,
filter: nil,
imageTransition: .crossDissolve(0.5),
completion: { response in
print(response.value) # UIImage
print(response.error) # NSError
}
)
You might first want to check response.result.isSuccess (or his brother response.result.isFailure) to make sure whether the image has been successfully retrieved or not.

Resources